Example #1
0
        /// <exception cref="Exception">Во время прослушивания входящего межпроцессорного подключения возникла непредвиденная ошибка.</exception>
        public async Task StartListen()
        {
            try
            {
                PipeServerF?.Disconnect();
                PipeServerF = new NamedPipeServerStream(NameOfPipeLineF);
                while (true)
                {
                    await PipeServerF.WaitForConnectionAsync().ConfigureAwait(false);

                    while (PipeServerF.IsConnected)
                    {
                        var buf = new byte[16];
                        await PipeServerF.ReadAsync(buf, 0, buf.Length).ConfigureAwait(false);

                        if (buf.All(b => b == 1))
                        {
                            Start();
                        }
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                var type = Type.GetType(ex.Source);
                if (type != null)
                {
                    if (type.IsAssignableFrom(GetType()))
                    {
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                var type = Type.GetType(ex.Source);
                if (type != null)
                {
                    if (type.IsAssignableFrom(GetType()))
                    {
                        var str = new StringBuilder();
                        str.AppendLine(
                            "Во время прослушивания входящего межпроцессорного подключения возникла непредвиденная ошибка.");
                        str.AppendLine($"{nameof(TurnKey)}: {TurnKey}.");
                        str.AppendLine($"{nameof(HookF)} != null: {HookF != IntPtr.Zero}.");
                        str.AppendLine(
                            $"{nameof(WorckingTaskF.Status)}: {Enum.GetName(typeof(TaskStatus), WorckingTaskF.Status)}.");
                        if (ProcessF != null)
                        {
                            str.AppendLine($"{nameof(ProcessF.ProcessName)}: {ProcessF.ProcessName}.");
                        }
                        throw new Exception(str.ToString(), ex)
                              {
                                  Source = GetType().AssemblyQualifiedName
                              };
                    }
                }
                throw;
            }
        }
Example #2
0
 public void OnPipeDisposed()
 {
     if (_serverPipe != null && _serverPipe.IsConnected)
     {
         _serverPipe?.Disconnect();
     }
     _serverPipe?.Close();
     _serverPipe?.Dispose();
     _serverPipe = null;
 }
Example #3
0
        public async Task During(CancellationToken cancellationToken = default)
        {
            try
            {
                await ProcessDataAsync(cancellationToken);

                Debug.WriteLine($"Disconnecting NamedPipeServerStream on {GetType().Name}");
                Pipe?.Disconnect();
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine($"ProcessDataAsync on {GetType().Name} cancelled");
            }
        }
        public static void ServerWhenDisplosedThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("unique2", PipeDirection.InOut))
            {
                server.Dispose();

                Assert.Throws<ObjectDisposedException>(() => server.Disconnect());  // disconnect when disposed
                Assert.Throws<ObjectDisposedException>(() => server.WaitForConnection());  // disconnect when disposed
                WhenDisposedPipeThrows(server);
            }
        }
Example #5
0
 private void Stop()
 {
     stream.Disconnect();
     Dispose();
 }
Example #6
0
    private static void PbindConnect()
    {
        PipeSecurity pipeSecurity   = new PipeSecurity();
        var          pipeAccessRule = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow);

        pipeSecurity.AddAccessRule(pipeAccessRule);
        var pipeServerStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.None, 4096, 4096, pipeSecurity);

        try
        {
            pipeServerStream.WaitForConnection();
            running = true;
            var pipeReader = new StreamReader(pipeServerStream);
            var pipeWriter = new StreamWriter(pipeServerStream);
            pipeWriter.AutoFlush = true;
            var ppass = pipeReader.ReadLine();


            var command = "";
            while (running)
            {
                if (ppass != secret)
                {
                    pipeWriter.WriteLine("Microsoft Error: 151337");
                }
                else
                {
                    while (running)
                    {
                        var u = "";
                        try
                        {
                            u = WindowsIdentity.GetCurrent().Name;
                        }
                        catch
                        {
                            u = Environment.UserName;
                        }
                        u += "*";
                        var dn   = Environment.UserDomainName;
                        var cn   = Environment.GetEnvironmentVariable("COMPUTERNAME");
                        var arch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
                        int pid  = Process.GetCurrentProcess().Id;
                        Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
                        var o  = String.Format("PBind-Connected: {0};{1};{2};{3};{4};", dn, u, cn, arch, pid);
                        var zo = Encrypt(encryption, o);
                        pipeWriter.WriteLine(zo);
                        var exitvt = new ManualResetEvent(false);
                        var output = new StringBuilder();

                        while (running)
                        {
                            var zz = Encrypt(encryption, "COMMAND");
                            pipeWriter.WriteLine(zz);
                            if (pipeServerStream.CanRead)
                            {
                                command = pipeReader.ReadLine();
                                if (!String.IsNullOrWhiteSpace(command))
                                {
                                    var sOutput2 = new StringWriter();

                                    var cmd = Decrypt(encryption, command);

                                    if (cmd.StartsWith("KILL"))
                                    {
                                        running = false;
                                        pipeServerStream.Disconnect();
                                        pipeServerStream.Close();
                                    }
                                    else if (cmd.ToLower().StartsWith("loadmodule"))
                                    {
                                        try
                                        {
                                            var module   = Regex.Replace(cmd, "loadmodule", "", RegexOptions.IgnoreCase);
                                            var assembly = Assembly.Load(Convert.FromBase64String(module));
                                        }
                                        catch (Exception e) { Console.WriteLine($"Error loading modules {e}"); }
                                        sOutput2.WriteLine("Module loaded successfully");
                                    }
                                    else if (cmd.ToLower().StartsWith("run-dll-background") || cmd.ToLower().StartsWith("run-exe-background"))
                                    {
                                        Thread t = new Thread(() => RunAssembly(cmd, true));
                                        t.Start();
                                        sOutput2.WriteLine("[+] Running task in background, run get-bg to get background output.");
                                        sOutput2.WriteLine("[*] Only run one task in the background at a time per implant.");
                                    }
                                    else if (cmd.ToLower().StartsWith("run-dll") || cmd.ToLower().StartsWith("run-exe"))
                                    {
                                        var oldOutput = Console.Out;
                                        Console.SetOut(sOutput2);
                                        sOutput2.WriteLine(RunAssembly((cmd)));
                                        Console.SetOut(oldOutput);
                                    }
                                    else if (cmd.ToLower() == "foo")
                                    {
                                        sOutput2.WriteLine("bar");
                                    }
                                    else if (cmd.ToLower() == "get-bg")
                                    {
                                        var backgroundTaskOutputString = backgroundTaskOutput.ToString();
                                        if (!string.IsNullOrEmpty(backgroundTaskOutputString))
                                        {
                                            output.Append(backgroundTaskOutputString);
                                        }
                                        else
                                        {
                                            sOutput2.WriteLine("[-] No output");
                                        }
                                    }
                                    else
                                    {
                                        var oldOutput = Console.Out;
                                        Console.SetOut(sOutput2);
                                        sOutput2.WriteLine(RunAssembly($"run-exe Core.Program Core {cmd}"));
                                        Console.SetOut(oldOutput);
                                    }

                                    output.Append(sOutput2.ToString());
                                    var result = Encrypt(encryption, output.ToString());

                                    pipeWriter.Flush();
                                    pipeWriter.WriteLine(result);
                                    pipeWriter.Flush();

                                    output.Clear();
                                    output.Length = 0;


                                    sOutput2.Flush();
                                    sOutput2.Close();
                                }
                            }
                            else
                            {
                                Console.WriteLine("$[-] Cannot read from pipe");
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }
Example #7
0
        /// <summary>
        /// Use the pipe classes in the System.IO.Pipes namespace to create the
        /// named pipe. This solution is recommended.
        /// </summary>
        public static void Run()
        {
            NamedPipeServerStream pipeServer = null;

            try
            {
                // Prepare the security attributes (the pipeSecurity parameter in
                // the constructor of NamedPipeServerStream) for the pipe. This
                // is optional. If pipeSecurity of NamedPipeServerStream is null,
                // the named pipe gets a default security descriptor.and the
                // handle cannot be inherited. The ACLs in the default security
                // descriptor of a pipe grant full control to the LocalSystem
                // account, (elevated) administrators, and the creator owner.
                // They also give only read access to members of the Everyone
                // group and the anonymous account. However, if you want to
                // customize the security permission of the pipe, (e.g. to allow
                // Authenticated Users to read from and write to the pipe), you
                // need to create a PipeSecurity object.
                PipeSecurity pipeSecurity = null;
                pipeSecurity = CreateSystemIOPipeSecurity();

                // Create the named pipe.
                pipeServer = new NamedPipeServerStream(
                    Program.PipeName,               // The unique pipe name.
                    PipeDirection.InOut,            // The pipe is duplex
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,   // Message-based communication
                    PipeOptions.None,               // No additional parameters
                    Program.BufferSize,             // Input buffer size
                    Program.BufferSize,             // Output buffer size
                    pipeSecurity,                   // Pipe security attributes
                    HandleInheritability.None       // Not inheritable
                    );

                Console.WriteLine("The named pipe ({0}) is created.",
                                  Program.FullPipeName);

                // Wait for the client to connect.
                Console.WriteLine("Waiting for the client's connection...");
                pipeServer.WaitForConnection();
                Console.WriteLine("Client is connected.");

                //
                // Receive a request from client.
                //
                // Note: The named pipe was created to support message-based
                // communication. This allows a reading process to read
                // varying-length messages precisely as sent by the writing
                // process. In this mode you should not use StreamWriter to write
                // the pipe, or use StreamReader to read the pipe. You can read
                // more about the difference from the article:
                // http://go.microsoft.com/?linkid=9721786.
                //

                string message;
                do
                {
                    byte[] bRequest = new byte[Program.BufferSize];
                    int    cbRequest = bRequest.Length, cbRead;

                    cbRead = pipeServer.Read(bRequest, 0, cbRequest);

                    // Unicode-encode the received byte array and trim all the
                    // '\0' characters at the end.
                    message = Encoding.Unicode.GetString(bRequest).TrimEnd('\0');
                    Console.WriteLine("Receive {0} bytes from client: \"{1}\"",
                                      cbRead, message);
                }while (!pipeServer.IsMessageComplete);

                //
                // Send a response from server to client.
                //

                message = Program.ResponseMessage;
                byte[] bResponse  = Encoding.Unicode.GetBytes(message);
                int    cbResponse = bResponse.Length;

                pipeServer.Write(bResponse, 0, cbResponse);

                Console.WriteLine("Send {0} bytes to client: \"{1}\"",
                                  cbResponse, message.TrimEnd('\0'));

                // Flush the pipe to allow the client to read the pipe's contents
                // before disconnecting. Then disconnect the client's connection.
                pipeServer.WaitForPipeDrain();
                pipeServer.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (pipeServer != null)
                {
                    pipeServer.Close();
                    pipeServer = null;
                }
            }
        }
Example #8
0
    public static async Task ClientServerOneWayOperations(
        string pipeName, PipeDirection serverDirection,
        bool asyncServerPipe, bool asyncClientPipe,
        bool asyncServerOps, bool asyncClientOps)
    {
        PipeDirection clientDirection = serverDirection == PipeDirection.Out ? PipeDirection.In : PipeDirection.Out;
        PipeOptions   serverOptions   = asyncServerPipe ? PipeOptions.Asynchronous : PipeOptions.None;
        PipeOptions   clientOptions   = asyncClientPipe ? PipeOptions.Asynchronous : PipeOptions.None;

        using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, serverOptions))
        {
            byte[] received   = new byte[] { 0 };
            Task   clientTask = Task.Run(async() =>
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, clientDirection, clientOptions))
                {
                    if (asyncClientOps)
                    {
                        await client.ConnectAsync();
                        if (clientDirection == PipeDirection.In)
                        {
                            received = await ReadBytesAsync(client, sendBytes.Length);
                        }
                        else
                        {
                            await WriteBytesAsync(client, sendBytes);
                        }
                    }
                    else
                    {
                        client.Connect();
                        if (clientDirection == PipeDirection.In)
                        {
                            received = ReadBytes(client, sendBytes.Length);
                        }
                        else
                        {
                            WriteBytes(client, sendBytes);
                        }
                    }
                }
            });

            if (asyncServerOps)
            {
                await server.WaitForConnectionAsync();

                if (serverDirection == PipeDirection.Out)
                {
                    await WriteBytesAsync(server, sendBytes);
                }
                else
                {
                    received = await ReadBytesAsync(server, sendBytes.Length);
                }
            }
            else
            {
                server.WaitForConnection();
                if (serverDirection == PipeDirection.Out)
                {
                    WriteBytes(server, sendBytes);
                }
                else
                {
                    received = ReadBytes(server, sendBytes.Length);
                }
            }

            await clientTask;
            Assert.Equal(sendBytes, received);

            server.Disconnect();
            Assert.False(server.IsConnected);
        }
    }
Example #9
0
        /// <summary>
        /// Listen for transfer requests
        /// </summary>
        public void Listen()
        {
            using (CancellationTokenRegistration CTR = Token.Register(() => Server.Dispose()))
            {
                while (!Token.IsCancellationRequested)
                {
                    //  This will contain the path
                    byte[] path = new byte[1024];
                    int    i    = 0;

                    Debug.WriteLine("Going to wait for a message.");

                    try
                    {
                        //  https://stackoverflow.com/questions/607872/what-is-a-good-way-to-shutdown-threads-blocked-on-namedpipeserverwaitforconnect/1191677
                        //  My first implementation was Server.WaitForConnection(),
                        //  but I realized that it was ignoring the cancellation.
                        //  I didn't like cancelling the Task without cancelling this first.
                        //  So, after lots of tries I decided to try to do it this way:
                        //  https://stackoverflow.com/questions/2700472/how-to-terminate-a-managed-thread-blocked-in-unmanaged-code/2700491#2700491
                        IAsyncResult asyncResult = Server.BeginWaitForConnection(null, null);

                        //  Wait for client to actually connect
                        if (asyncResult.AsyncWaitHandle.WaitOne())
                        {
                            Server.EndWaitForConnection(asyncResult);
                            // success
                            Debug.WriteLine("Waited, now we're in.");

                            if (Server.CanRead)
                            {
                                int c;
                                while (i < 1024)
                                {
                                    //  Prefered using ReadByte as I don't know exactly how many bytes I'll have to read
                                    c = Server.ReadByte();

                                    //  Make it end gracefully (c == -1 means end of stream)
                                    if (c == -1)
                                    {
                                        i = 1024;
                                    }
                                    else
                                    {
                                        path[i++] = (byte)c;
                                    }
                                }

                                Debug.WriteLine("read " + Encoding.Unicode.GetString(path));

                                /*
                                 * Why trimming \0?? That's just the c-style string terminator, right?
                                 * Well, while testing, I noticed that FileInfo (in Send.cs) was *always* throwing
                                 * an ArgumentException, stating that there were invalid characters in the path.
                                 * It was really weird, every string I passed to it was correct!
                                 * I could even open the file in Windows Explorer, just by copy-pasting!
                                 * Well, after *ONE F*****G HOUR DEBUGGING*, I discovered that FileInfo
                                 * doesn't like the \0 after the string, because it parses it as a valid character.
                                 * THANKS.
                                 */
                                OpenWindow(Encoding.Unicode.GetString(path).Trim('\0'));
                            }
                        }

                        //  Disconnect the server and wait for other requests
                        Server.Disconnect();
                    }
                    catch (Exception /*e*/)
                    {
                        Debug.WriteLine("PipeListener ended");
                    }
                }
            }
        }
        /*
         * private void RunEventLooper()
         * {
         *  NamedPipeServerStream eventPipeServer = null;
         *  while (_shouldRun)
         *  {
         *      // Allocate the named pipe endpoint
         *      eventPipeServer = new NamedPipeServerStream(EVENT_PIPE, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.None, INBUFFSIZE, OUTBUFFSIZE, _pipeSa);
         *
         *      // Wait for a client to connect
         *      eventPipeServer.WaitForConnection();
         *
         *      //Spawn a new thread for each request and continue waiting
         *      Thread t = new Thread(ProcessEvent);
         *      t.Start(eventPipeServer);
         *  }
         *  eventPipeServer.Close();
         * }
         */
        void ProcessEvent(NamedPipeServerStream eventPipeServer)
        {
            //NamedPipeServerStream eventPipeServer = o as NamedPipeServerStream;
            try
            {
                // Read the request from the client. Once the client has
                // written to the pipe its security token will be available.
                var msg = ProcessSingleReceivedMessage(eventPipeServer);

                // The received data must be in XML format
                XmlDocument xml_doc           = new XmlDocument();
                var         xmlReaderSettings = new XmlReaderSettings {
                    CheckCharacters = false
                };
                using (var stringReader = new StringReader(msg))
                {
                    using (var xmlReader = XmlReader.Create(stringReader, xmlReaderSettings))
                    {
                        xml_doc.Load(xmlReader);
                    }
                }
                var xml = xml_doc.DocumentElement;

                ProgramStatus.Instance.IncLogRate();
                string mode;

                // Handle differently depending on the ElementName
                switch (xml.Name)
                {
                case WK_PROCESS_EVENT:
                    var type = xml.Attributes[WK_PROCESS_EVENT_TYPE].InnerText;

                    if (type == WK_PROCESS_EVENT_TYPE_SPAWNED)
                    {
                        var parentPid = uint.Parse(xml.Attributes[WK_PROCESS_EVENT_PARENT_PID].InnerText);
                        var pid       = uint.Parse(xml.Attributes[WK_PROCESS_EVENT_PID].InnerText);
                        ProgramStatus.Instance.AddPid(parentPid, pid);
                    }
                    else if (type == WK_PROCESS_EVENT_TYPE_DEAD)
                    {
                        var pid = uint.Parse(xml.Attributes[WK_PROCESS_EVENT_PID].InnerText);
                        ProgramStatus.Instance.RemovePid(pid);
                    }

                    break;

                case WK_FILE_EVENT:
                    if (Settings.Default.LOG_FS)
                    {
                        mode = xml.Attributes[WK_FILE_EVENT_MODE].InnerText;
                        if (mode == WK_FILE_CREATED || mode == WK_FILE_OPENED || mode == WK_FILE_DELETED)
                        {
                            ProgramStatus.Instance.NotifyFileAccess(xml.Attributes[WK_FILE_EVENT_PATH].InnerText);
                        }
                        else if (mode == WK_FILE_RENAMED)
                        {
                            // Convert raw bytes received by the message pump into a conveniente struct and parse the strings
                            var oldPath = xml.Attributes[WK_FILE_EVENT_OLD_PATH].InnerText;
                            var newPath = xml.Attributes[WK_FILE_EVENT_NEW_PATH].InnerText;
                            // Now notify the file rename
                            ProgramStatus.Instance.NotifyFileRename(oldPath, newPath);
                        }
                    }
                    break;

                case WK_REGISTRY_EVENT:
                    if (Settings.Default.LOG_REG)
                    {
                        mode = xml.Attributes[WK_REGISTRY_EVENT_MODE].InnerText;
                        if (mode == WK_KEY_OPENED || mode == WK_KEY_CREATED)
                        {
                            var path = xml.Attributes[WK_REGISTRY_EVENT_PATH].InnerText;
                            ProgramStatus.Instance.NotifyRegistryAccess(path);
                        }
                    }
                    break;
                }

                // Send the ACK ( ACK = 1 )
                eventPipeServer.Write(ENCODED_ACK, 0, ENCODED_ACK.Length);
                eventPipeServer.Flush();
                //eventPipeServer.WaitForPipeDrain();
                eventPipeServer.Disconnect();
            }
            catch (Exception e)
            {
                try
                {
                    if (eventPipeServer.IsConnected)
                    {
                        eventPipeServer.Disconnect();
                    }
                }
                catch (Exception e1)
                {
                    // GIVEUP
                }
            }
        }
Example #11
0
        private NamedPipeServerStream CreateOpenTabPipeServer(string pipeName)
        {
            var ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                                                AccessControlType.Allow));
            ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));

            var pipeClientConnection = new NamedPipeServerStream(pipeName, PipeDirection.In, 5,
                                                                 PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);


            pipeClientConnection.BeginWaitForConnection(asyncResult =>
            {
                using (var conn = (NamedPipeServerStream)asyncResult.AsyncState)
                {
                    conn.EndWaitForConnection(asyncResult);

                    var newServer = CreateOpenTabPipeServer(pipeName);

                    var streamReader = new StreamReader(conn);

                    while (true)
                    {
                        string file = streamReader.ReadLine();

                        if (file == ":KILL:")
                        {
                            if (pipeClientConnection.IsConnected)
                            {
                                pipeClientConnection.Disconnect();
                            }

                            pipeClientConnection.Close();
                            pipeClientConnection.Dispose();

                            if (newServer.IsConnected)
                            {
                                newServer.Disconnect();
                            }

                            newServer.Close();
                            newServer.Dispose();

                            Dispatcher.Invoke(Close);
                        }
                        if (file == ":EOF:")
                        {
                            break;
                        }

                        Dispatcher.Invoke(() =>
                        {
                            var alreadyOpen = EditorTabs.FirstOrDefault(x => x.FilePath == file);
                            if (alreadyOpen != null)
                            {
                                TabControl.SelectedIndex = EditorTabs.IndexOf(alreadyOpen);
                                return;
                            }

                            var tab = CreateEditorTab();
                            if (!tab.OpenFileInteractive(file))
                            {
                                return;
                            }
                            EditorTabs.Add(tab);
                            TabControl.SelectedIndex = EditorTabs.Count - 1;
                        });
                    }
                }
            }, pipeClientConnection);

            return(pipeClientConnection);
        }
Example #12
0
        //Based on https://github.com/malcomvetter/NamedPipes
        public static void RunScoutService(string scout_np, string simulator_np, string log)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;
            Logger logger      = new Logger(currentPath + log);
            bool   running     = true;
            bool   privileged  = false;

            string technique, opsec, simpfath, simrpath, duser, user, simbinary, cleanup;

            technique = opsec = simpfath = simrpath = duser = user = simbinary = cleanup = "";
            Process parentprocess = null;
            int     pbsleep, tsleep;

            pbsleep = tsleep = 0;
            System.Threading.Thread.Sleep(1500);

            try
            {
                using (var pipeServer = new NamedPipeServerStream(scout_np, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message))
                {
                    logger.TimestampInfo("Starting scout namedpipe service with PID:" + Process.GetCurrentProcess().Id);
                    while (running)
                    {
                        var reader = new StreamReader(pipeServer);
                        var writer = new StreamWriter(pipeServer);

                        //logger.TimestampInfo("Waiting for client connection...");
                        pipeServer.WaitForConnection();
                        //logger.TimestampInfo("Client connected!");

                        var line = reader.ReadLine();

                        logger.TimestampInfo("Received from client: " + line);

                        if (line.ToLower().Equals("syn"))
                        {
                            //logger.TimestampInfo("sending back to client: " + "SYN/ACK");
                            writer.WriteLine("SYN/ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().Equals("auditpol"))
                        {
                            writer.WriteLine(System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(Recon.GetAuditPolicy())));
                            writer.Flush();
                        }
                        else if (line.ToLower().Equals("wef"))
                        {
                            writer.WriteLine(System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(Recon.GetWefSettings())));
                            writer.Flush();
                        }
                        else if (line.ToLower().Equals("pws"))
                        {
                            writer.WriteLine(System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(Recon.GetPwsLoggingSettings())));
                            writer.Flush();
                        }
                        else if (line.ToLower().Equals("ps"))
                        {
                            writer.WriteLine(System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(Recon.GetProcs())));
                            writer.Flush();
                        }
                        else if (line.ToLower().Equals("svcs"))
                        {
                            writer.WriteLine(System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(Recon.GetServices())));
                            writer.Flush();
                        }
                        else if (line.ToLower().Equals("cmdline"))
                        {
                            writer.WriteLine(System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(Recon.GetCmdlineAudittingSettings())));
                            writer.Flush();
                        }

                        else if (line.ToLower().StartsWith("recon:"))
                        {
                            string payload = "";
                            if (line.Replace("recon:", "").Equals("privileged"))
                            {
                                privileged = true;
                            }
                            parentprocess = Recon.GetHostProcess(privileged);
                            if (parentprocess != null && Recon.GetExplorer() != null)
                            {
                                duser = Recon.GetProcessOwnerWmi(Recon.GetExplorer());
                                user  = duser.Split('\\')[1];
                                logger.TimestampInfo(String.Format("Recon identified {0} logged in. Process to Spoof: {1} PID: {2}", duser, parentprocess.ProcessName, parentprocess.Id));
                                payload = String.Format("{0},{1},{2},{3}", duser, parentprocess.ProcessName, parentprocess.Id, privileged.ToString());
                            }
                            else
                            {
                                payload = ",,,";
                                logger.TimestampInfo("Recon did not identify any logged users");
                            }
                            writer.WriteLine(payload);
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("sc:"))
                        {
                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("technique:"))
                        {
                            technique = line.Replace("technique:", "");
                            //logger.TimestampInfo("Got params from client");
                            //logger.TimestampInfo("sending back to client: " + "ACK");
                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("pbsleep:"))
                        {
                            pbsleep = Int32.Parse(line.Replace("pbsleep:", ""));
                            //logger.TimestampInfo("Got params from client");
                            //logger.TimestampInfo("sending back to client: " + "ACK");
                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("tsleep:"))
                        {
                            tsleep = Int32.Parse(line.Replace("tsleep:", ""));
                            //logger.TimestampInfo("Got params from client");
                            //logger.TimestampInfo("sending back to client: " + "ACK");
                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("opsec:"))
                        {
                            opsec = line.Replace("opsec:", "");
                            //logger.TimestampInfo("Got opsec technique from client");
                            //logger.TimestampInfo("sending back to client: " + "ACK");
                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("cleanup:"))
                        {
                            cleanup = line.Replace("cleanup:", "");
                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.ToLower().StartsWith("simrpath:"))
                        {
                            simrpath = line.Replace("simrpath:", "");
                            //logger.TimestampInfo("sending back to client: " + "ACK");
                            //simpath = "C:\\Users\\" + loggeduser + "\\Downloads\\" + simbin;
                            simpfath = "C:\\Users\\" + user + "\\" + simrpath;
                            int index = simrpath.LastIndexOf(@"\");
                            simbinary = simrpath.Substring(index + 1);

                            writer.WriteLine("ACK");
                            writer.Flush();
                        }
                        else if (line.Equals("act"))
                        {
                            logger.TimestampInfo("Received act!");
                            //logger.TimestampInfo("sending back to client: " + "ACK");
                            writer.WriteLine("ACK");
                            writer.Flush();

                            if (opsec.Equals("ppid"))
                            {
                                logger.TimestampInfo("Using Parent Process Spoofing technique for Opsec");
                                logger.TimestampInfo("Spoofing " + parentprocess.ProcessName + " PID: " + parentprocess.Id.ToString());
                                logger.TimestampInfo("Executing: " + simpfath + " /n");
                                //Launcher.SpoofParent(parentprocess.Id, simpath, simbin + " " + cmdline);
                                //Launcher.SpoofParent(parentprocess.Id, simpfath, simrpath + " /s");

                                Launcher.SpoofParent(parentprocess.Id, simpfath, simbinary + " /n");
                                //Launcher.SpoofParent(parentprocess.Id, simpfath, simbinary + " /s");

                                System.Threading.Thread.Sleep(3000);
                                logger.TimestampInfo("Sending payload to Scout Aggent through namedpipe: " + "technique:" + technique + " pbsleep:" + pbsleep.ToString() + " tsleep:" + tsleep.ToString() + " cleanup:" + cleanup);
                                RunNoAuthClient(simulator_np, "technique:" + technique + " pbsleep:" + pbsleep.ToString() + " tsleep:" + tsleep.ToString() + " cleanup:" + cleanup);
                                System.Threading.Thread.Sleep(2000);
                            }
                        }
                        else if (line.ToLower().Equals("quit"))
                        {
                            logger.TimestampInfo("Received quit! Exitting namedpipe");
                            //logger.TimestampInfo("sending back to client: " + "quit");
                            writer.WriteLine("quit");
                            writer.Flush();
                            running = false;
                        }
                        pipeServer.Disconnect();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.TimestampInfo(ex.ToString());
                logger.TimestampInfo(ex.Message.ToString());
            }
        }
Example #13
0
        /// <summary>
        /// Listen from service for commands from core or configurator
        /// </summary>
        public static void StartListening()
        {
            if (connected)
            {
                return;            //only one connection...
            }
            Async.Queue("MB Connection", () =>
            {
                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);

                PipeSecurity pipeSa = new PipeSecurity();
                pipeSa.SetAccessRule(new PipeAccessRule(sid,
                                                        PipeAccessRights.ReadWrite, AccessControlType.Allow));


                using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBServiceController.MBSERVICE_IN_PIPE, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.None, 1024, 1024, pipeSa))
                {
                    connected    = true;
                    bool process = true;
                    while (process)
                    {
                        pipe.WaitForConnection(); //wait for the core to tell us something
                        try
                        {
                            // Read the request from the sender.
                            StreamReader sr = new StreamReader(pipe);

                            string command = sr.ReadLine();
                            switch (command.ToLower())
                            {
                            case IPCCommands.ReloadKernel:     //don't use this yet - need to figure out how to unload first do a shutdown and restart
                                //something changed, we need to re-load everything
                                Logger.ReportInfo("Re-loading kernel due to request from client.");
                                Kernel.Init(KernelLoadDirective.ShadowPlugins);
                                break;

                            case IPCCommands.ReloadConfig:
                                //re-load the main config file
                                Kernel.Instance.ReLoadConfig();
                                break;

                            case IPCCommands.Shutdown:
                                //close Service
                                Logger.ReportInfo("Shutting down due to request from client.");
                                MainWindow.Instance.Shutdown();
                                break;

                            case IPCCommands.Restart:
                                //restart Service
                                Logger.ReportInfo("Restarting due to request from client.");
                                MainWindow.Instance.Restart();
                                break;

                            case IPCCommands.CancelRefresh:
                                //cancel any running refresh
                                MainWindow.Instance.CancelRefresh();
                                break;

                            case IPCCommands.ForceRebuild:
                                //force a re-build of the library - used with new version that requires it
                                Logger.ReportInfo("Forcing re-build of library due to request from client.");
                                MainWindow.Instance.ForceRebuild();
                                break;

                            case IPCCommands.Refresh:
                                Logger.ReportInfo("Refreshing now due to request from client.");
                                MainWindow.Instance.RefreshNow();
                                break;

                            case IPCCommands.CloseConnection:
                                //exit this connection
                                Logger.ReportInfo("Client requested we stop listening.");
                                process = false;
                                break;
                            }
                            pipe.Disconnect();
                        }
                        catch (IOException e)
                        {
                            Logger.ReportException("Error in MB connection", e);
                        }
                    }
                    pipe.Close();
                    connected = false;
                }
            });
        }
Example #14
0
        private void MainLoop()
        {
            var numberFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();

            numberFormat.NumberDecimalSeparator = ".";
            numberFormat.NumberDecimalDigits    = 3;

            const int sizeValueString = 11;
            uint      frameNumber     = 0;
            uint      totalTime       = 0;
            var       firstPass       = true;
            var       totalTimeSb     = new StringBuilder(sizeValueString);

            int bufferSize;

            unsafe
            {
                bufferSize = sizeof(FRAMETIME_PIPE_DATA);
            }

            var buffer = new byte[bufferSize];

            do //while (ContinueAcceptingConnections);
            {
                try
                {
                    try
                    {
                        unsafe
                        {
                            fixed(void *rowData = buffer)
                            while (false == m_stopReadWriteLoops)
                            {
                                int readedCount;

                                lock (m_pipeStreamLocker)
                                {
                                    SetFlag(PipeReaderState.PipeIO, true);
                                    try
                                    {
                                        readedCount = m_pipeStream.Read(buffer, 0, bufferSize);
                                    }
                                    finally
                                    {
                                        SetFlag(PipeReaderState.PipeIO, false);
                                    }
                                }

                                if (readedCount == 0)
                                {
                                    break;
                                }

                                if (m_stopReadWriteLoops)
                                {
                                    break;
                                }

                                if (false == EnabledWritingFile)
                                {
                                    continue;
                                }

                                ++frameNumber;

                                var ppipeData = (FRAMETIME_PIPE_DATA *)rowData;
                                var delta     = ppipeData->dwFrametime;


                                string strValue;

                                if (false == m_writeFrapsFileFormat)
                                {
                                    strValue = string.Empty;

                                    if (false == firstPass)
                                    {
                                        strValue = ", ";
                                    }
                                    else
                                    {
                                        firstPass = false;
                                    }

                                    strValue += ((float)delta / 1000).ToString(numberFormat);
                                }
                                else
                                {
                                    totalTime += delta;

                                    strValue  = frameNumber.ToString("D5").ReplaceInplaceLeadingChars('0', ' ');
                                    strValue += ",";

                                    var totalTimeString = ((float)totalTime / 1000.0).ToString(numberFormat);
                                    if (totalTimeString.Length < sizeValueString)
                                    {
                                        totalTimeString = totalTimeSb
                                                          .Append(' ', sizeValueString - totalTimeString.Length)
                                                          .Append(totalTimeString)
                                                          .Append(Environment.NewLine)
                                                          .ToString();
                                        totalTimeSb.Clear();
                                    }

                                    strValue += totalTimeString;
                                }


                                var stringBytes = Encoding.ASCII.GetBytes(strValue);

                                lock (m_fileStreamLocker)
                                {
                                    if (m_fileStream != null)
                                    {
                                        m_fileStream.Write(stringBytes, 0, stringBytes.Length);
                                    }
                                    else
                                    {
                                        OpenFile();

                                        frameNumber = 0;
                                        totalTime   = 0;
                                        firstPass   = true;
                                    }
                                }
                            }
                        }
                    }
                    catch (System.OperationCanceledException)
                    {
                    }
                    catch (Exception exception)
                    {
                        m_lastException = exception;
                        SetFlag(PipeReaderState.Error, true);
                    }
                }
                finally
                {
                    SetFlag(PipeReaderState.PipeIO, false);
                    CloseFile();

                    lock (m_pipeStream)
                    {
                        if (m_pipeStream != null)
                        {
                            m_pipeStream.Disconnect();
                        }
                    }
                    SetFlag(PipeReaderState.ConnectionAccepted, false);

                    if (false == ContinueAcceptingConnections)
                    {
                        ClosePipe();
                    }
                }


                if (false == ContinueAcceptingConnections)
                {
                    return;
                }

                lock (m_pipeStreamLocker)
                {
                    try
                    {
                        WaitForConnection();
                        OpenFile();
                    }
                    catch (OperationCanceledException exception)
                    {
                        return;
                    }
                    catch (Exception exception)
                    {
                        m_lastException = exception;
                        SetFlag(PipeReaderState.Error, true);
                    }

                    frameNumber = 0;
                    totalTime   = 0;
                    firstPass   = true;

                    m_stopReadWriteLoops = false;
                }
            } while (ContinueAcceptingConnections);
        }
Example #15
0
        private void ServerThread()
        {
            try
            {
                var pipeSecurity = new PipeSecurity();
                var sid          = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                var par          = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow);
                pipeSecurity.AddAccessRule(par);

                using (
                    var pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1,
                                                               PipeTransmissionMode.Byte, PipeOptions.None, 2048, 2048, pipeSecurity))
                {
                    // Read the request from the client. Once the client has
                    // written to the pipe its security token will be available.
                    using (var sr = new StreamReader(pipeServer))
                        using (var sw = new StreamWriter(pipeServer))
                        {
                            _serverStartedSuccessfully = true;
                            _pipeServerStartedEvent.Set();

                            //logger.Trace("NamedPipeServerStream thread created.");
                            while (!_aborted)
                            {
                                // Wait for a client to connect
                                pipeServer.WaitForConnection();

                                //logger.Trace("Client connected.");
                                try
                                {
                                    sw.AutoFlush = true;

                                    // If we are preparing the Shutdown, we no longer accept messages
                                    if (_preparingShutdown)
                                    {
                                        sw.WriteLine("SHUTDOWN|");
                                        //Logger.Info("Received message while preparing Shutdown. Message is rejected!");
                                    }
                                    else
                                    {
                                        // Verify our identity to the connected client using a
                                        // string that the client anticipates.
                                        sw.WriteLine("HELLO|" + _serverName);

                                        // Read the command from the connected client.
                                        string command = sr.ReadLine();
                                        //Logger.Trace("Received: " + command);

                                        sw.WriteLine("OK");

                                        var eventThread = new Thread(EventThread);
                                        eventThread.Start(command);
                                    }
                                }
                                catch (IOException)
                                {
                                    // Catch the IOException that is raised if the pipe is broken
                                    // or disconnected.
                                }
                                pipeServer.Disconnect();
                            }
                        }
                }
            }

            catch (ThreadAbortException)
            {
                Stop();
            }
            catch (Exception)
            {
                _serverStartedSuccessfully = false;
            }
            finally
            {
                _pipeServerStartedEvent.Set();
            }
        } // ServerThread()
Example #16
0
        static void Main(string[] args)
        {
            if (!_Created || args == null || args.Length == 0)
            {
                return;
            }

            string ProcessName = args[0];

            Console.WriteLine("-----------------------------------------------");
            Console.WriteLine($"本程式將監控 {ProcessName} 是否持續運作");
            Console.WriteLine($"倘若偵測到 {ProcessName} 關閉時,將自動重新啟動");
            Console.WriteLine($"若需關閉 {ProcessName} 時,請先將本程式關閉");
            Console.WriteLine("-----------------------------------------------\n");

            var          PipeServer = new NamedPipeServerStream("WatchDog");
            StreamReader Reader     = new StreamReader(PipeServer);
            StreamWriter Writer     = new StreamWriter(PipeServer);

            Console.WriteLine($"等待 {ProcessName} 上線");
            PipeServer.WaitForConnection();
            Console.WriteLine($"連線成功");

            DateTime StartTime = DateTime.Now;

            while (true)
            {
                if (_TimeoutCounter > 3)
                {
                    Console.CursorTop += 3;
                    Console.WriteLine();
                    Console.WriteLine($"{ProcessName} 無回應,嘗試重新啟動");

                    Process[] ProcessList = null;
                    if (args != null && args.Length > 0)
                    {
                        ProcessList = Process.GetProcessesByName(ProcessName);
                    }
                    if (ProcessList != null && ProcessList.Length == 1)
                    {
                        Console.WriteLine($"{ProcessName} 異常,強制關閉程式");
                        ProcessList[0].Kill();
                    }
                    Console.WriteLine("重新啟動中...");
                    Process.Start(ProcessName);

                    _TimeoutCounter = 0;

                    PipeServer.Disconnect();
                    PipeServer.Dispose();

                    PipeServer = new NamedPipeServerStream("WatchDog");
                    Reader     = new StreamReader(PipeServer);
                    Writer     = new StreamWriter(PipeServer);
                    PipeServer.WaitForConnection();
                    Console.WriteLine("重啟成功");
                    _RebootCounter++;
                    StartTime = DateTime.Now;
                    Console.WriteLine($"累計重啟次數: {_RebootCounter}");
                }

                _Current = Reader.ReadLine();
                if (_Current != null)
                {
                    TimeSpan Duration = DateTime.Now - StartTime;

                    Console.WriteLine("-----------------------------------------------");
                    Console.WriteLine($"程式已運行: {Duration.Days.ToString("0000")}天 {Duration.Hours.ToString("00")}時 {Duration.Minutes.ToString("00")}分 {Duration.Seconds.ToString("00")}秒");
                    Console.WriteLine("-----------------------------------------------");
                    Console.SetCursorPosition(0, Console.CursorTop - 3);
                }

                Thread.Sleep(1000);
                if (_Last == _Current)
                {
                    _TimeoutCounter++;
                }
                else
                {
                    _TimeoutCounter = 0;
                    _Last           = _Current;
                }
            }
        }
 public void Cleanup()
 {
     protocol = null;
     pipe.Disconnect();
     pipe.Dispose();
 }
Example #18
0
        public void Start()
        {
            Running    = true;
            pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut);
            sec.ServerLog.Log(Logging.LogLevel.INFORMATION, "IPC server running at pipe " + pipeName);
            while (Running)
            {
                try
                {
                    pipeServer.WaitForConnection();
                    int         bytesRead       = 0;
                    byte[]      buffer          = new byte[1024]; //Reads 8k messages
                    List <byte> constructedData = new List <byte>();
                    while ((bytesRead = pipeServer.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        if (bytesRead != buffer.Length)
                        {
                            for (int i = 0; i < bytesRead; i++)
                            {
                                constructedData.Add(buffer[i]);
                            }
                        }
                        else
                        {
                            constructedData.AddRange(buffer);
                        }
                    }
                    string receivedData = Encoding.UTF8.GetString(constructedData.ToArray()).Trim();
                    foreach (var ln in receivedData.Split('\n'))
                    {
                        string request = "null";
                        try
                        {
                            var line = ln.Trim();
                            if (line == "")
                            {
                                continue;
                            }
                            string[] cmd = line.Split(' ');
                            request = cmd[0];
                            sec.ServerLog.Log(Logging.LogLevel.INFORMATION, "Received IPC Request {0}", request);
                            switch (cmd[0])
                            {
                            case "STOP-SERVER":
                                sec.Server.Stop();
                                break;

                            case "REGISTER-CGI-APPLICATION":
                                string[] s            = line.Split('"');
                                string   cgiExtension = s[1].Trim();
                                string   cgiBinPath   = s[3].Trim();
                                sec.Server.RegisterCGIClient(cgiExtension, cgiBinPath);
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            sec.ServerLog.Log(Logging.LogLevel.ERROR, "Error completing IPC request \"{0}\". Message: {1}", request, ex.Message);
                            continue;
                        }
                    }
                    pipeServer.Disconnect();
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
        private void PacketPumpProc()
        {
            NamedPipeServerStream localPipeServer = _pipeServer;

            AutoResetEvent localPacketAvailable            = _packetAvailable;
            AutoResetEvent localTerminatePacketPump        = _terminatePacketPump;
            ConcurrentQueue <INodePacket> localPacketQueue = _packetQueue;

            DateTime originalWaitStartTime = DateTime.UtcNow;
            bool     gotValidConnection    = false;

            while (!gotValidConnection)
            {
                gotValidConnection = true;
                DateTime restartWaitTime = DateTime.UtcNow;

                // We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting
                // to attach.  This prevents each attempt from resetting the timer.
                TimeSpan usedWaitTime      = restartWaitTime - originalWaitStartTime;
                int      waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds);

                try
                {
                    // Wait for a connection
#if FEATURE_APM
                    IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null);
                    CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);
                    bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false);
#else
                    Task connectionTask = localPipeServer.WaitForConnectionAsync();
                    CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);
                    bool connected = connectionTask.Wait(waitTimeRemaining);
#endif
                    if (!connected)
                    {
                        CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us.  Exiting comm thread.");
                        ChangeLinkStatus(LinkStatus.ConnectionFailed);
                        return;
                    }

                    CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent");
#if FEATURE_APM
                    localPipeServer.EndWaitForConnection(resultForConnection);
#endif

                    // The handshake protocol is a series of int exchanges.  The host sends us a each component, and we
                    // verify it. Afterwards, the host sends an "End of Handshake" signal, to which we respond in kind.
                    // Once the handshake is complete, both sides can be assured the other is ready to accept data.
                    Handshake handshake = GetHandshake();
                    try
                    {
                        int[] handshakeComponents = handshake.RetrieveHandshakeComponents();
                        for (int i = 0; i < handshakeComponents.Length; i++)
                        {
                            int handshakePart = _pipeServer.ReadIntForHandshake(i == 0 ? (byte?)CommunicationsUtilities.handshakeVersion : null /* this will disconnect a < 16.8 host; it expects leading 00 or F5 or 06. 0x00 is a wildcard */
#if NETCOREAPP2_1_OR_GREATER || MONO
                                                                                , ClientConnectTimeout                                          /* wait a long time for the handshake from this side */
#endif
                                                                                );

                            if (handshakePart != handshakeComponents[i])
                            {
                                CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshakePart, handshakeComponents[i]);
                                _pipeServer.WriteIntForHandshake(i + 1);
                                gotValidConnection = false;
                                break;
                            }
                        }

                        if (gotValidConnection)
                        {
                            // To ensure that our handshake and theirs have the same number of bytes, receive and send a magic number indicating EOS.
#if NETCOREAPP2_1_OR_GREATER || MONO
                            _pipeServer.ReadEndOfHandshakeSignal(false, ClientConnectTimeout); /* wait a long time for the handshake from this side */
#else
                            _pipeServer.ReadEndOfHandshakeSignal(false);
#endif
                            CommunicationsUtilities.Trace("Successfully connected to parent.");
                            _pipeServer.WriteEndOfHandshakeSignal();

#if FEATURE_SECURITY_PERMISSIONS
                            // We will only talk to a host that was started by the same user as us.  Even though the pipe access is set to only allow this user, we want to ensure they
                            // haven't attempted to change those permissions out from under us.  This ensures that the only way they can truly gain access is to be impersonating the
                            // user we were started by.
                            WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
                            WindowsIdentity clientIdentity  = null;
                            localPipeServer.RunAsClient(delegate() { clientIdentity = WindowsIdentity.GetCurrent(true); });

                            if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name);
                                gotValidConnection = false;
                                continue;
                            }
#endif
                        }
                    }
                    catch (IOException e)
                    {
                        // We will get here when:
                        // 1. The host (OOP main node) connects to us, it immediately checks for user privileges
                        //    and if they don't match it disconnects immediately leaving us still trying to read the blank handshake
                        // 2. The host is too old sending us bits we automatically reject in the handshake
                        // 3. We expected to read the EndOfHandshake signal, but we received something else
                        CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message);

                        gotValidConnection = false;
                    }
                    catch (InvalidOperationException)
                    {
                        gotValidConnection = false;
                    }

                    if (!gotValidConnection)
                    {
                        if (localPipeServer.IsConnected)
                        {
                            localPipeServer.Disconnect();
                        }
                        continue;
                    }

                    ChangeLinkStatus(LinkStatus.Active);
                }
                catch (Exception e) when(!ExceptionHandling.IsCriticalException(e))
                {
                    CommunicationsUtilities.Trace("Client connection failed.  Exiting comm thread. {0}", e);
                    if (localPipeServer.IsConnected)
                    {
                        localPipeServer.Disconnect();
                    }

                    ExceptionHandling.DumpExceptionToFile(e);
                    ChangeLinkStatus(LinkStatus.Failed);
                    return;
                }
            }

            RunReadLoop(
                new BufferedReadStream(_pipeServer),
                _pipeServer,
                localPacketQueue, localPacketAvailable, localTerminatePacketPump);

            CommunicationsUtilities.Trace("Ending read loop");

            try
            {
                if (localPipeServer.IsConnected)
                {
#if NETCOREAPP // OperatingSystem.IsWindows() is new in .NET 5.0
                    if (OperatingSystem.IsWindows())
#endif
                    {
                        localPipeServer.WaitForPipeDrain();
                    }

                    localPipeServer.Disconnect();
                }
            }
            catch (Exception)
            {
                // We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing.
            }
        }
Example #20
0
        public bool StartServer(string eventName, string pipeName, Func <uint, byte[], Tuple <ErrCode, byte[], uint> > cmdProc)
        {
            if (m_ServerThread != null)
            {
                return(false);
            }

            m_StopFlag   = false;
            m_PulseEvent = new AutoResetEvent(false);
            var    eventConnect = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
            string trustee      = "NT Service\\EpgTimer Service";

            try
            {
                // "EpgTimer Service"のサービスセキュリティ識別子(Service-specific SID)に対するアクセス許可を追加する
                EventWaitHandleSecurity sec = eventConnect.GetAccessControl();
                sec.AddAccessRule(new EventWaitHandleAccessRule(trustee, EventWaitHandleRights.Synchronize, AccessControlType.Allow));
                eventConnect.SetAccessControl(sec);
            }
            catch
            {
                trustee = null;
            }
            var pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024,
                                                 null, System.IO.HandleInheritability.None, trustee == null ? 0 : PipeAccessRights.ChangePermissions);

            if (trustee != null)
            {
                try
                {
                    PipeSecurity sec = pipe.GetAccessControl();
                    sec.AddAccessRule(new PipeAccessRule(trustee, PipeAccessRights.ReadWrite, AccessControlType.Allow));
                    pipe.SetAccessControl(sec);
                }
                catch
                {
                }
            }

            m_ServerThread = new Thread(new ThreadStart(() =>
            {
                using (eventConnect)
                    using (pipe)
                    {
                        while (m_StopFlag == false)
                        {
                            pipe.BeginWaitForConnection(asyncResult =>
                            {
                                try
                                {
                                    pipe.EndWaitForConnection(asyncResult);
                                    m_PulseEvent.Set();
                                }
                                catch (ObjectDisposedException)
                                {
                                }
                            }, null);
                            eventConnect.Set();
                            m_PulseEvent.WaitOne();
                            if (pipe.IsConnected)
                            {
                                byte[] bHead = new byte[8];
                                if (ReadAll(pipe, bHead, 0, 8) == 8)
                                {
                                    uint cmdParam  = BitConverter.ToUInt32(bHead, 0);
                                    byte[] cmdData = new byte[BitConverter.ToUInt32(bHead, 4)];
                                    if (ReadAll(pipe, cmdData, 0, cmdData.Length) == cmdData.Length)
                                    {
                                        Tuple <ErrCode, byte[], uint> res = cmdProc.Invoke(cmdParam, cmdData);
                                        BitConverter.GetBytes((uint)res.Item1).CopyTo(bHead, 0);
                                        BitConverter.GetBytes(res.Item2 == null ? 0 : res.Item2.Length).CopyTo(bHead, 4);
                                        pipe.Write(bHead, 0, 8);
                                        if (res.Item2 != null && res.Item2.Length > 0)
                                        {
                                            pipe.Write(res.Item2, 0, res.Item2.Length);
                                        }
                                    }
                                }
                                pipe.WaitForPipeDrain();
                                pipe.Disconnect();
                            }
                        }
                    }
            }));
            m_ServerThread.Start();

            return(true);
        }
        public async Task OneWayReadWrites(PipeOptions serverOptions, PipeOptions clientOptions, bool asyncServerOps, bool asyncClientOps)
        {
            using (NamedPipePair pair = CreateNamedPipePair(serverOptions, clientOptions))
            {
                NamedPipeClientStream client = pair.clientStream;
                NamedPipeServerStream server = pair.serverStream;
                byte[] received   = new byte[] { 0 };
                Task   clientTask = Task.Run(async() =>
                {
                    if (asyncClientOps)
                    {
                        await client.ConnectAsync();

                        if (pair.writeToServer)
                        {
                            received = await ReadBytesAsync(client, sendBytes.Length);
                        }
                        else
                        {
                            await WriteBytesAsync(client, sendBytes);
                        }
                    }
                    else
                    {
                        client.Connect();
                        if (pair.writeToServer)
                        {
                            received = ReadBytes(client, sendBytes.Length);
                        }
                        else
                        {
                            WriteBytes(client, sendBytes);
                        }
                    }
                });
                if (asyncServerOps)
                {
                    await server.WaitForConnectionAsync();

                    if (pair.writeToServer)
                    {
                        await WriteBytesAsync(server, sendBytes);
                    }
                    else
                    {
                        received = await ReadBytesAsync(server, sendBytes.Length);
                    }
                }
                else
                {
                    server.WaitForConnection();
                    if (pair.writeToServer)
                    {
                        WriteBytes(server, sendBytes);
                    }
                    else
                    {
                        received = ReadBytes(server, sendBytes.Length);
                    }
                }

                await clientTask;
                Assert.Equal(sendBytes, received);

                server.Disconnect();
                Assert.False(server.IsConnected);
            }
        }
Example #22
0
        /* A Named Pipe Server listening for requests on files to start and stop monitoring.
         * When an incoming request comes with the 'opened' flag, it grabs the file path,
         * creates an instance of a protected file using the 'ProtectFile' class and adds to the
         * list of active protected files; then starting the file monitoring functions. If an
         * incoming request has the 'closed' flag, it will remove the closed file from the active
         * protected files list. Being either 'opened' or 'closed', it always checks if the active
         * protected files list contains any files and will turn on/off all monitoring functions
         * when needed.
         *
         * Param: None.
         * Return: None.
         */
        public void FileMonitor()
        {
            String call, option, file;

            PipeSecurity ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
            ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));
            NamedPipeServerStream pipeServer = new NamedPipeServerStream("FileMonitor", PipeDirection.InOut, 10,
                                                                         PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps);

            StreamReader sr = new StreamReader(pipeServer);

            while (true)
            {
                try
                {
                    pipeServer.WaitForConnection();
                    call   = sr.ReadLine();
                    option = call.Split('|').First();
                    file   = call.Split('|').Last();
                    if (option.Equals("opened"))
                    {
                        if (!protectedFiles.Any())
                        {
                            EnableClipboardMonitor();
                            DisableBlacklistProcesses();
                            EnableWindowMonitor();
                            EnableFileCopyMonitor();
                        }
                        protectedFiles.Add(new ProtectFile(file));
                    }
                    else if (option.Equals("closed"))
                    {
                        String fileName = file.Split('\\').Last();
                        MessageBox.Show("Please ensure to either re-encrypt file '" + fileName + "', or remove from the protected area. Last access to this file has been logged.");
                        if (protectedFiles.Any())
                        {
                            foreach (var pfile in protectedFiles.ToList())
                            {
                                if (pfile.GetFile().Equals(file))
                                {
                                    protectedFiles.Remove(pfile);
                                }
                            }
                            if (!protectedFiles.Any())
                            {
                                DisableClipboardMonitor();
                                EnableBlacklistProcesses();
                                DisableWindowMonitor();
                                DisableFileCopyMonitor();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    pipeServer.WaitForPipeDrain();
                    if (pipeServer.IsConnected)
                    {
                        pipeServer.Disconnect();
                    }
                }
            }
        }
Example #23
0
        private void ReceiveDataFromClient()
        {
            var _pipeServer = new NamedPipeServerStream(秘密字符串 + "2", PipeDirection.InOut, 2);
            var sr          = new StreamReader(_pipeServer);

            while (true)
            {
                try
                {
                    _pipeServer.WaitForConnection(); //Waiting
                    Log("收到管道连接!");
                    while (_pipeServer.CanRead)
                    {
                        var data = sr.ReadLine();
                        if (data == null)
                        {
                            break;
                        }
                        var recData = data.Split(' ');
                        switch (recData[0])
                        {
                        case "pluse":
                            _timeout     = TimeSpan.FromSeconds(Convert.ToInt32(recData[1]));
                            _restartFlag = Convert.ToInt32(recData[2]);
                            Log("收到心跳包{0} {1} {2}", _timeout, _restartFlag, (DateTime.Now - _lastPluse).TotalSeconds);
                            _lastPluse = DateTime.Now;
                            break;

                        case "restartWithoutLogin":
                            LastRestartMsg = "上次重启原因:收到非登录重启的命令";
                            RestartWithoutLogin();
                            break;

                        case "restart":
                            Log("收到强制重启命令");
                            LastRestartMsg = "上次重启原因:收到强制重启命令";
                            Restart(true);
                            break;

                        case "complete":
                            Log("帐号刷完");
                            _currentAccount.CoolDown = Next6();
                            if (_usingFakeMAC)
                            {
                                if (择一个可用帐号())
                                {
                                    TryLaunchAutoLogin();
                                }
                            }
                            break;

                        default:
                            Log("未实现命令:{0}", string.Join(" ", recData));
                            break;
                        }
                    }
                    Thread.Sleep(1000);
                    _pipeServer.Disconnect();

                    Log("管道连接断开!");
                }
                catch (Exception ex)
                {
                    Log(ex.Message);
                }
                Thread.Sleep(1000);
            }
        }
Example #24
0
        public async Task Listen()
        {
            var ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule(
                                 new SecurityIdentifier(_allowedSid),
                                 PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                                 AccessControlType.Allow));

            var networkSid = new SecurityIdentifier("S-1-5-2");

            // deny remote connections.
            ps.AddAccessRule(new PipeAccessRule(
                                 networkSid,
                                 PipeAccessRights.FullControl,
                                 System.Security.AccessControl.AccessControlType.Deny));

            var pipeName = NamedPipeNameFactory.GetPipeName(_allowedSid, _allowedPid);

            Logger.Instance.Log($"Listening on named pipe {pipeName}.", LogLevel.Debug);

            Logger.Instance.Log($"Access allowed only for ProcessID {_allowedPid} and children", LogLevel.Debug);

            _ = Task.Factory.StartNew(CancelIfAllowedProcessEnds, _cancellationTokenSource.Token,
                                      TaskCreationOptions.LongRunning, TaskScheduler.Current);

            do
            {
                using (NamedPipeServerStream dataPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                  PipeTransmissionMode.Message, PipeOptions.Asynchronous, Settings.BufferSize, Settings.BufferSize, ps))
                {
                    using (NamedPipeServerStream controlPipe = new NamedPipeServerStream(pipeName + "_control", PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                         PipeTransmissionMode.Message, PipeOptions.Asynchronous, Settings.BufferSize, Settings.BufferSize, ps))
                    {
                        Logger.Instance.Log("NamedPipeServer listening.", LogLevel.Debug);
                        Task.WaitAll(
                            new Task[]
                        {
                            dataPipe.WaitForConnectionAsync(_cancellationTokenSource.Token),
                            controlPipe.WaitForConnectionAsync(_cancellationTokenSource.Token),
                        },
                            _cancellationTokenSource.Token
                            );

                        if (dataPipe.IsConnected && controlPipe.IsConnected && !_cancellationTokenSource.IsCancellationRequested)
                        {
                            var connection = new Connection()
                            {
                                ControlStream = controlPipe, DataStream = dataPipe
                            };

                            ConnectionKeepAliveThread.Start(connection);

                            Logger.Instance.Log("Incoming Connection.", LogLevel.Info);

                            var clientPid = dataPipe.GetClientProcessId();

                            if (!IsAuthorized(clientPid, _allowedPid))
                            {
                                Logger.Instance.Log($"Unauthorized access from PID {clientPid}", LogLevel.Warning);

                                await controlPipe.WriteAsync($"{Constants.TOKEN_ERROR}Unauthorized. (Different gsudo.exe?) {Constants.TOKEN_ERROR}").ConfigureAwait(false);

                                await controlPipe.FlushAsync().ConfigureAwait(false);

                                controlPipe.WaitForPipeDrain();

                                dataPipe.Disconnect();
                                controlPipe.Disconnect();

                                // kill the server.
                                return;
                            }

                            ConnectionAccepted?.Invoke(this, connection);

                            while (connection.IsAlive)
                            {
                                await Task.Delay(10).ConfigureAwait(false);
                            }

                            ConnectionClosed?.Invoke(this, connection);
                            Logger.Instance.Log("Connection Closed.", LogLevel.Info);
                        }
                    }
                }
            } while (!_singleUse && !_cancellationTokenSource.IsCancellationRequested);
            Logger.Instance.Log("Listener Closed.", LogLevel.Debug);
        }
        public static void ServerNotConnectedThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("tempnotconnected", PipeDirection.InOut, 1))
            {
                // doesn't throw exceptions
                PipeTransmissionMode transmitMode = server.TransmissionMode;
                Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
                    RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.Equal(0, server.InBufferSize);
                    Assert.Equal(0, server.OutBufferSize);
                }
                else
                {
                    Assert.Throws<PlatformNotSupportedException>(() => server.InBufferSize);
                    Assert.Throws<PlatformNotSupportedException>(() => server.OutBufferSize);
                }
                PipeTransmissionMode readMode = server.ReadMode;
                server.ReadMode = PipeTransmissionMode.Byte;

                Assert.Throws<InvalidOperationException>(() => server.WriteByte(5));
                Assert.Throws<InvalidOperationException>(() => server.ReadByte());
                Assert.Throws<InvalidOperationException>(() => server.Disconnect());    // disconnect when not connected 
                Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete);
            }
        }
        /// <summary>
        /// This method handles the asynchronous message pump.  It waits for messages to show up on the queue
        /// and calls FireDataAvailable for each such packet.  It will terminate when the terminate event is
        /// set.
        /// </summary>
        private void PacketPumpProc()
        {
            NamedPipeServerStream localPipeServer = _pipeServer;
            PipeStream            localWritePipe  = _pipeServer;
            PipeStream            localReadPipe   = _pipeServer;

            AutoResetEvent localPacketAvailable            = _packetAvailable;
            AutoResetEvent localTerminatePacketPump        = _terminatePacketPump;
            ConcurrentQueue <INodePacket> localPacketQueue = _packetQueue;

            DateTime originalWaitStartTime = DateTime.UtcNow;
            bool     gotValidConnection    = false;

            while (!gotValidConnection)
            {
                DateTime restartWaitTime = DateTime.UtcNow;

                // We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting
                // to attach.  This prevents each attempt from resetting the timer.
                TimeSpan usedWaitTime      = restartWaitTime - originalWaitStartTime;
                int      waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds);

                try
                {
                    // Wait for a connection
#if FEATURE_APM
                    IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null);
#else
                    Task connectionTask = localPipeServer.WaitForConnectionAsync();
#endif
                    CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);

#if FEATURE_APM
                    bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false);
#else
                    bool connected = connectionTask.Wait(waitTimeRemaining);
#endif
                    if (!connected)
                    {
                        CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us.  Exiting comm thread.");
                        ChangeLinkStatus(LinkStatus.ConnectionFailed);
                        return;
                    }

                    CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent");
#if FEATURE_APM
                    localPipeServer.EndWaitForConnection(resultForConnection);
#endif

                    // The handshake protocol is a simple long exchange.  The host sends us a long, and we
                    // respond with another long.  Once the handshake is complete, both sides can be assured the
                    // other is ready to accept data.
                    // To avoid mixing client and server builds, the long is the MSBuild binary timestamp.

                    // Compatibility issue here.
                    // Previous builds of MSBuild 4.0 would exchange just a byte.
                    // Host would send either 0x5F or 0x60 depending on whether it was the toolset or not respectively.
                    // Client would return either 0xF5 or 0x06 respectively.
                    // Therefore an old host on a machine with new clients running will hang,
                    // sending a byte and waiting for a byte until it eventually times out;
                    // because the new client will want 7 more bytes before it returns anything.
                    // The other way around is not a problem, because the old client would immediately return the (wrong)
                    // byte on receiving the first byte of the long sent by the new host, and the new host would disconnect.
                    // To avoid the hang, special case here:
                    // Make sure our handshakes always start with 00.
                    // If we received ONLY one byte AND it's 0x5F or 0x60, return 0xFF (it doesn't matter what as long as
                    // it will cause the host to reject us; new hosts expect 00 and old hosts expect F5 or 06).
                    try
                    {
                        long handshake = localReadPipe.ReadLongForHandshake(/* reject these leads */ new byte[] { 0x5F, 0x60 }, 0xFF /* this will disconnect the host; it expects leading 00 or F5 or 06 */
#if NETCOREAPP2_1 || MONO
                                                                            , ClientConnectTimeout                                   /* wait a long time for the handshake from this side */
#endif
                                                                            );

#if FEATURE_SECURITY_PERMISSIONS
                        WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
#endif

                        if (handshake != GetHostHandshake())
                        {
                            CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshake, GetHostHandshake());
                            localPipeServer.Disconnect();
                            continue;
                        }

#if FEATURE_SECURITY_PERMISSIONS
                        // We will only talk to a host that was started by the same user as us.  Even though the pipe access is set to only allow this user, we want to ensure they
                        // haven't attempted to change those permissions out from under us.  This ensures that the only way they can truly gain access is to be impersonating the
                        // user we were started by.
                        WindowsIdentity clientIdentity = null;
                        localPipeServer.RunAsClient(delegate() { clientIdentity = WindowsIdentity.GetCurrent(true); });

                        if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name);
                            localPipeServer.Disconnect();
                            continue;
                        }
#endif
                    }
                    catch (IOException e)
                    {
                        // We will get here when:
                        // 1. The host (OOP main node) connects to us, it immediately checks for user privileges
                        //    and if they don't match it disconnects immediately leaving us still trying to read the blank handshake
                        // 2. The host is too old sending us bits we automatically reject in the handshake
                        CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message);
                        if (localPipeServer.IsConnected)
                        {
                            localPipeServer.Disconnect();
                        }

                        continue;
                    }

                    gotValidConnection = true;

                    CommunicationsUtilities.Trace("Writing handshake to parent");
                    localWritePipe.WriteLongForHandshake(GetClientHandshake());
                    ChangeLinkStatus(LinkStatus.Active);
                }
                catch (Exception e)
                {
                    if (ExceptionHandling.IsCriticalException(e))
                    {
                        throw;
                    }

                    CommunicationsUtilities.Trace("Client connection failed.  Exiting comm thread. {0}", e);
                    if (localPipeServer.IsConnected)
                    {
                        localPipeServer.Disconnect();
                    }

                    ExceptionHandling.DumpExceptionToFile(e);
                    ChangeLinkStatus(LinkStatus.Failed);
                    return;
                }
            }

            RunReadLoop(
                new BufferedReadStream(localReadPipe),
                localWritePipe,
                localPacketQueue, localPacketAvailable, localTerminatePacketPump);

            CommunicationsUtilities.Trace("Ending read loop");

            try
            {
                if (localPipeServer.IsConnected)
                {
                    localPipeServer.WaitForPipeDrain();
                    localPipeServer.Disconnect();
                }
            }
            catch (Exception)
            {
                // We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing.
            }
        }
        public static async Task ServerAfterDisconnectThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("unique3", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "unique3", PipeDirection.In))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                await clientConnect;

                Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete);
                Assert.Throws<InvalidOperationException>(() => server.WaitForConnection());
                await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync());

                server.Disconnect();

                Assert.Throws<InvalidOperationException>(() => server.Disconnect());    // double disconnect

                AfterDisconnectWriteOnlyPipeThrows(server);
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // on Unix, InOut doesn't result in the same Disconnect-based errors due to allowing for other connections
            {
                using (NamedPipeServerStream server = new NamedPipeServerStream("unique3", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                using (NamedPipeClientStream client = new NamedPipeClientStream("unique3"))
                {
                    Task clientConnect = client.ConnectAsync();
                    server.WaitForConnection();
                    await clientConnect;

                    Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete);
                    Assert.Throws<InvalidOperationException>(() => server.WaitForConnection());
                    await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync());

                    server.Disconnect();

                    Assert.Throws<InvalidOperationException>(() => server.Disconnect());    // double disconnect

                    AfterDisconnectReadWritePipeThrows(server);
                }
            }
        }
 public void Disconnect()
 {
     _pipeServer.Disconnect();
 }
Example #29
0
        public void Unix_MultipleServerDisposal_DoesntDeletePipe()
        {
            // Test for when multiple servers are created and linked to the same FIFO. The original ServerStream
            // that created the FIFO is disposed. The other servers should still be valid and useable.
            string serverName = GetUniquePipeName();

            var server1 = new NamedPipeServerStream(serverName, PipeDirection.In); // Creates the FIFO
            var server2 = new NamedPipeServerStream(serverName, PipeDirection.In);
            var client1 = new NamedPipeClientStream(".", serverName, PipeDirection.Out);
            var client2 = new NamedPipeClientStream(".", serverName, PipeDirection.Out);

            Task server1Task = server1.WaitForConnectionAsync(); // Opens a handle to the FIFO
            Task server2Task = server2.WaitForConnectionAsync(); // Opens a handle to the same FIFO as server1

            Task client1Task = client1.ConnectAsync();
            Task.WaitAll(server1Task, server2Task, client1Task); // client1 connects to server1 AND server2

            Assert.True(server1.IsConnected);
            Assert.True(server2.IsConnected);

            // Get rid of client1/server1 and make sure server2 isn't connected (so that it can connect to client2)
            server1.Dispose();
            client1.Dispose();
            server2.Disconnect();
            Assert.False(server2.IsConnected);

            server2Task = server2.WaitForConnectionAsync(); // Opens a handle to the same FIFO
            Task client2Task = client2.ConnectAsync(); 
            Task.WaitAll(server2Task, client2Task); // Should not block!
            Assert.True(server2.IsConnected);
        }
        public static bool StartListening()
        {
            if (connected)
            {
                return(false);           //only one connection...
            }
            if (Application.RunningOnExtender)
            {
                Logger.ReportInfo("Running on an extender.  Not starting client listener.");
                return(true); //no comms for extenders
            }

            NamedPipeServerStream pipe;

            try
            {
                pipe = new NamedPipeServerStream(Kernel.MBCLIENT_MUTEX_ID);
            }
            catch (IOException)
            {
                Logger.ReportInfo("Client listener already going - activating that instance of MB...");
                //already started - must be another instance of MB Core - tell it to come to front
                string entryPoint = EntryPointResolver.EntryPointPath;
                if (string.IsNullOrEmpty(entryPoint))
                {
                    SendCommandToCore("activate");
                }
                else //nav to the proper entrypoint
                {
                    Logger.ReportInfo("Navigating current instance to entrypoint " + entryPoint);
                    SendCommandToCore("activateentrypoint," + entryPoint);
                }
                //and exit
                return(false);
            }

            connected = true;

            Async.Queue("MBClient Listener", () =>
            {
                bool process = true;
                while (process)
                {
                    pipe.WaitForConnection(); //wait for someone to tell us something
                    string[] commandAndArgs;
                    try
                    {
                        // Read the request from the client.
                        StreamReader sr = new StreamReader(pipe);

                        commandAndArgs = sr.ReadLine().Split(',');
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Error during IPC communication.  Attempting to re-start listener", e);
                        try
                        {
                            //be sure we're cleaned up
                            pipe.Disconnect();
                            pipe.Close();
                        }
                        catch
                        { //we don't care if these fail now - and they very well may
                        }
                        finally
                        {
                            connected = false;
                        }
                        StartListening();
                        return;
                    }
                    try
                    {
                        string command = commandAndArgs[0];
                        switch (command.ToLower())
                        {
                        case "play":
                            //request to play something - our argument will be the GUID of the item to play
                            Guid id = new Guid(commandAndArgs[1]);
                            Logger.ReportInfo("Playing ...");
                            //to be implemented...
                            break;

                        case "activateentrypoint":
                            //re-load ourselves and nav to the entrypoint
                            Kernel.Instance.ReLoadRoot();
                            Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ =>
                            {
                                MediaBrowser.Application.CurrentInstance.LaunchEntryPoint(commandAndArgs[1]);
                            });
                            //and tell MC to navigate to us
                            Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.ReturnToApplication();
                            break;

                        case "activate":
                            Logger.ReportInfo("Asked to activate by another process..");
                            //if we were in an entrypoint and we just got told to activate - we need to re-load and go to real root
                            if (Application.CurrentInstance.IsInEntryPoint)
                            {
                                Kernel.Instance.ReLoadRoot();
                                Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ =>
                                {
                                    MediaBrowser.Application.CurrentInstance.LaunchEntryPoint("");     //this will start at root
                                });
                            }
                            else
                            {
                                //just need to back up to the root
                                Application.CurrentInstance.BackToRoot();
                            }

                            // set npv visibility according to current state
                            if (Application.MediaCenterEnvironment.MediaExperience != null && Application.MediaCenterEnvironment.MediaExperience.Transport != null)
                            {
                                Application.CurrentInstance.ShowNowPlaying = Application.MediaCenterEnvironment.MediaExperience.Transport.PlayState == Microsoft.MediaCenter.PlayState.Playing;
                            }

                            //tell MC to navigate to us
                            Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.ReturnToApplication();
                            break;

                        case "shutdown":
                            //close MB
                            Logger.ReportInfo("Shutting down due to request from a client (possibly new instance of MB).");
                            Application.CurrentInstance.Close();
                            break;

                        case "closeconnection":
                            //exit this connection
                            Logger.ReportInfo("Service requested we stop listening.");
                            process = false;
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Error trying to process IPC command", e);
                    }
                    try
                    {
                        pipe.Disconnect();
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Unexpected Error trying to close IPC connection", e);
                    }
                }
                pipe.Close();
                connected = false;
            });
            return(true);
        }
Example #31
0
        public void DoEncode(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string passStr = Processing.GetResourceString("x264_pass");
            string status  = Processing.GetResourceString("x264_encoding_status");

            bool use64BitEncoder = AppSettings.Use64BitEncoders &&
                                   AppSettings.X26464Installed &&
                                   Environment.Is64BitOperatingSystem;

            X264Profile encProfile = (X264Profile)_jobInfo.VideoProfile;

            if (!_jobInfo.EncodingProfile.Deinterlace && _jobInfo.VideoStream.Interlaced)
            {
                _jobInfo.VideoStream.Interlaced = false;
            }

            Size resizeTo = VideoHelper.GetTargetSize(_jobInfo);

            if (string.IsNullOrEmpty(_jobInfo.AviSynthScript))
            {
                GenerateAviSynthScript(resizeTo);
            }

            string inputFile = _jobInfo.AviSynthScript;
            string outFile   =
                Processing.CreateTempFile(
                    string.IsNullOrEmpty(_jobInfo.TempOutput) ? _jobInfo.BaseName : _jobInfo.TempOutput, "encoded.264");

            int targetBitrate = 0;

            if (_jobInfo.EncodingProfile.TargetFileSize > 0)
            {
                targetBitrate = Processing.CalculateVideoBitrate(_jobInfo);
            }

            int encodeMode = encProfile.EncodingMode;

            if ((encodeMode == 2) || (encodeMode == 3))
            {
                _pass = string.Format(" {1} {0:0}; ", _jobInfo.StreamId, passStr);
            }

            _frameCount = _jobInfo.VideoStream.FrameCount;

            _bw.ReportProgress(-10, status + _pass.Replace("; ", string.Empty));
            _bw.ReportProgress(0, status);

            string argument = X264CommandLineGenerator.Generate(encProfile,
                                                                targetBitrate,
                                                                resizeTo.Width,
                                                                resizeTo.Height,
                                                                _jobInfo.StreamId,
                                                                _jobInfo.VideoStream.FrameRateEnumerator,
                                                                _jobInfo.VideoStream.FrameRateDenominator,
                                                                _jobInfo.EncodingProfile.StereoType,
                                                                _jobInfo.VideoStream.PicSize,

                                                                // check if we use 64 bit version
                                                                //use64BitEncoder ? "-" : inputFile,
                                                                "-",
                                                                outFile);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, use64BitEncoder ? Executable64 : Executable);

            using (Process encoder = new Process())
            {
                ProcessStartInfo parameter = new ProcessStartInfo(localExecutable)
                {
                    WorkingDirectory      = AppSettings.DemuxLocation,
                    Arguments             = argument,
                    CreateNoWindow        = true,
                    UseShellExecute       = false,
                    RedirectStandardError = true,
                    RedirectStandardInput = use64BitEncoder
                };
                encoder.StartInfo = parameter;

                encoder.ErrorDataReceived += OnDataReceived;

                Log.InfoFormat("start parameter: x264 {0:s}", argument);

                bool started;
                bool decStarted;

                NamedPipeServerStream decodePipe = new NamedPipeServerStream(AppSettings.DecodeNamedPipeName,
                                                                             PipeDirection.InOut, 3,
                                                                             PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
                decodePipe.BeginWaitForConnection(DecoderConnected, null);

                Size originalSize = new Size(_jobInfo.VideoStream.Width, _jobInfo.VideoStream.Height);
                if (_jobInfo.VideoStream.Width < _jobInfo.VideoStream.Height * _jobInfo.VideoStream.AspectRatio)
                {
                    originalSize.Width = (int)(_jobInfo.VideoStream.Height * _jobInfo.VideoStream.AspectRatio);
                    int temp;
                    Math.DivRem(originalSize.Width, 2, out temp);
                    originalSize.Width += temp;
                }

                Process decoder = FfMpeg.GenerateDecodeProcess(inputFile,
                                                               AppSettings.Use64BitEncoders && AppSettings.UseFfmpegScaling,
                                                               originalSize, _jobInfo.VideoStream.AspectRatio,
                                                               _jobInfo.VideoStream.CropRect, resizeTo);
                try
                {
                    decStarted = decoder.Start();
                }
                catch (Exception ex)
                {
                    decStarted = false;
                    Log.ErrorFormat("avconv exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                try
                {
                    started = encoder.Start();
                }
                catch (Exception ex)
                {
                    started = false;
                    Log.ErrorFormat("x264 encoder exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                _startTime = DateTime.Now;

                if (started && decStarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();

                    decoder.PriorityClass = AppSettings.GetProcessPriority();
                    decoder.BeginErrorReadLine();

                    Thread pipeReadThread = new Thread(() =>
                    {
                        try
                        {
                            if (encoder != null)
                            {
                                ReadThreadStart(decodePipe, encoder);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }
                    });
                    pipeReadThread.Start();
                    pipeReadThread.Priority = ThreadPriority.BelowNormal;
                    decoder.Exited         += (o, args) =>
                    {
                        try
                        {
                            decodePipe.Disconnect();
                            decodePipe.Close();
                            decodePipe.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }
                    };
                    encoder.Exited += (o, args) => pipeReadThread.Abort();

                    while (!encoder.HasExited && !decoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                        {
                            encoder.Kill();
                            decoder.Kill();
                        }
                        Thread.Sleep(200);
                    }
                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();
                    decoder.WaitForExit(10000);
                    decoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);
                }
            }

            if (_jobInfo.ExitCode == 0)
            {
                if ((encProfile.EncodingMode == 2 && _jobInfo.StreamId == 2) ||
                    (encProfile.EncodingMode == 3 && _jobInfo.StreamId == 3) ||
                    (encProfile.EncodingMode < 2 || _jobInfo.StreamId > 3))
                {
                    _jobInfo.VideoStream.Encoded     = true;
                    _jobInfo.VideoStream.IsRawStream = true;

                    _jobInfo.TempFiles.Add(_jobInfo.VideoStream.TempFile);
                    _jobInfo.VideoStream.TempFile = outFile;

                    try
                    {
                        _jobInfo.MediaInfo = Processing.GetMediaInfo(_jobInfo.VideoStream.TempFile);
                    }
                    catch (TimeoutException ex)
                    {
                        Log.Error(ex);
                    }
                    _jobInfo.VideoStream = VideoHelper.GetStreamInfo(_jobInfo.MediaInfo, _jobInfo.VideoStream,
                                                                     _jobInfo.EncodingProfile.OutFormat ==
                                                                     OutputType.OutputBluRay);

                    _jobInfo.TempFiles.Add(Path.Combine(AppSettings.DemuxLocation, "x264_2pass.log"));
                    _jobInfo.TempFiles.Add(Path.Combine(AppSettings.DemuxLocation, "x264_2pass.log.mbtree"));
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthScript);
                    _jobInfo.TempFiles.Add(_jobInfo.FfIndexFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthStereoConfig);
                }
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }
Example #32
0
        public bool StartServer(string strEventName, string strPipeName, Action <CMD_STREAM, CMD_STREAM> pfnCmdProc)
        {
            if (pfnCmdProc == null || strEventName.Length == 0 || strPipeName.Length == 0)
            {
                return(false);
            }
            if (m_ServerThread != null)
            {
                return(false);
            }

            m_StopFlag     = false;
            m_PulseEvent   = new AutoResetEvent(false);
            m_ServerThread = new Thread(new ThreadStart(() =>
            {
                using (EventWaitHandle eventConnect = new EventWaitHandle(false, EventResetMode.AutoReset, strEventName))
                    using (NamedPipeServerStream pipe = new NamedPipeServerStream(
                               strPipeName.Substring(strPipeName.StartsWith("\\\\.\\pipe\\", StringComparison.OrdinalIgnoreCase) ? 9 : 0),
                               PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                    {
                        while (m_StopFlag == false)
                        {
                            pipe.BeginWaitForConnection(asyncResult =>
                            {
                                try
                                {
                                    if (m_StopFlag == false)
                                    {
                                        pipe.EndWaitForConnection(asyncResult);
                                        m_PulseEvent.Set();
                                    }
                                }
                                catch (ObjectDisposedException)
                                {
                                }
                            }, null);
                            eventConnect.Set();
                            m_PulseEvent.WaitOne();
                            if (pipe.IsConnected)
                            {
                                try
                                {
                                    byte[] bHead = new byte[8];
                                    if (pipe.Read(bHead, 0, 8) == 8)
                                    {
                                        CMD_STREAM stCmd = new CMD_STREAM();
                                        stCmd.uiParam    = BitConverter.ToUInt32(bHead, 0);
                                        stCmd.uiSize     = BitConverter.ToUInt32(bHead, 4);
                                        stCmd.bData      = stCmd.uiSize == 0 ? null : new byte[stCmd.uiSize];
                                        if (stCmd.uiSize == 0 || pipe.Read(stCmd.bData, 0, stCmd.bData.Length) == stCmd.bData.Length)
                                        {
                                            CMD_STREAM stRes = new CMD_STREAM();
                                            pfnCmdProc.Invoke(stCmd, stRes);
                                            if (stRes.uiParam == (uint)ErrCode.CMD_NEXT)
                                            {
                                                // Emun用の繰り返しは対応しない
                                                throw new InvalidOperationException();
                                            }
                                            else if (stRes.uiParam != (uint)ErrCode.CMD_NO_RES)
                                            {
                                                BitConverter.GetBytes(stRes.uiParam).CopyTo(bHead, 0);
                                                BitConverter.GetBytes(stRes.uiSize).CopyTo(bHead, 4);
                                                pipe.Write(bHead, 0, 8);
                                                if (stRes.uiSize != 0 && stRes.bData != null && stRes.bData.Length >= stRes.uiSize)
                                                {
                                                    pipe.Write(stRes.bData, 0, (int)stRes.uiSize);
                                                }
                                            }
                                        }
                                    }
                                    pipe.WaitForPipeDrain();
                                    pipe.Disconnect();
                                }
                                catch
                                {
                                    // Read & Write 中に切断されると例外が起きるはずなので一応 catch しておく
                                }
                            }
                        }
                    }
            }));
            m_ServerThread.Start();

            return(true);
        }