Esempio n. 1
0
 /// <summary>
 /// Runs the 
 /// </summary>
 public static void Run()
 {
     const uint NORMAL_PRIORITY_CLASS = 0x0020;
     string Path = Environment.CurrentDirectory + @"\" + (Program.projectName.ToString() == "Ultimatium" ? "BlackOpsMP.exe" : "iw5mp.exe");
     string Arguments = Program.Arguments;
     PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
     STARTUPINFO sInfo = new STARTUPINFO();
     SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
     SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
     pSec.nLength = Marshal.SizeOf(pSec);
     tSec.nLength = Marshal.SizeOf(tSec);
     bool Initialized = CreateProcess(Path, Arguments,
     ref pSec, ref tSec, false, NORMAL_PRIORITY_CLASS,
     IntPtr.Zero, null, ref sInfo, out pInfo);
     if (Initialized)
     {
         Log.Write("Launching " + Program.projectName + "...");
         Log.Write("Successful launch. PID: " + pInfo.dwProcessId);
         Log.Write("Happy gaming!");
         Environment.Exit(0x0);
     }
     else
     {
         Log.Write("ERROR: Could not launch " + Program.projectName + ". Press any key to exit.");
         Console.ReadKey();
         Environment.Exit(0x3);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Creates the process.
        /// </summary>
        /// <param name="ProcessName">Name of the process.</param>
        /// <param name="CommandLine">The command line.</param>
        /// <exception cref="System.Exception">Failure</exception>
        public static void CreateProcess(string ProcessName, string CommandLine)
        {
            Log.WriteLine("CreateProcess(" + ProcessName + ", " + CommandLine + ")");
            STARTUPINFO SInfo = new STARTUPINFO();
            PROCESS_INFORMATION PInfo = new PROCESS_INFORMATION();
            Log.WriteLine("Try Connect to DBG");
            DbgUiConnectToDbg();
            Log.WriteLine("Try CreateProcess");
            if (!CreateProcess(null, new StringBuilder(ProcessName).Append(" ").Append(CommandLine), null, null, false, 0x1 | 0x2, null, null, ref SInfo, ref PInfo))
            {
                // May be must be run under Administrator.

                if (Global.IsAdministrator())
                {
                    Log.WriteLine("Creating process failed.");
                }
                else
                {
                    RestartWithAdministrator();
                }
            }
            Log.WriteLine("Try Stop Debugging");
            DbgUiStopDebugging(PInfo.hProcess);
            CloseHandle(PInfo.hProcess);
            CloseHandle(PInfo.hThread);
            Log.WriteLine("Created Process.");
        }
Esempio n. 3
0
 public static bool LaunchPathAsUser(string path)
 {
     unsafe
     {
         IntPtr token;
         string dir = new FileInfo(path).Directory.FullName;
         STARTUPINFO startup = new STARTUPINFO
         {
             cb = 0, // Probably incredibly dangerous and unsafe, but you can't use sizeof(STARTUPINFO).
             lpReserved = null,
             lpDesktop = "winsta0\\default",
             lpTitle = null,
             dwFlags = 0,
             cbReserved2 = 0,
             lpReserved2 = IntPtr.Zero
         };
         PROCESS_INFORMATION procinfo;
         WTSQueryUserToken(WTSGetActiveConsoleSessionId(), out token);
         return CreateProcessAsUser(
             token,
             path,
             null,
             null,
             null,
             false,
             0,
             IntPtr.Zero,
             dir,
             ref startup,
             out procinfo
             );
     }
 }
Esempio n. 4
0
 public static extern bool CreateProcess(string lpApplicationName,
        string lpCommandLine, IntPtr lpProcessAttributes,
        IntPtr lpThreadAttributes,
        bool bInheritHandles, ProcessCreationFlags dwCreationFlags,
        IntPtr lpEnvironment, string lpCurrentDirectory,
        ref STARTUPINFO lpStartupInfo,
        out PROCESS_INFORMATION lpProcessInformation);
Esempio n. 5
0
        public static PROCESS_INFORMATION CreateProcess(
            string lpApplicationName,
            string lpCommandLine,
            IntPtr lpProcessAttributes,
            IntPtr lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            string lpCurrentDirectory)
        {
            var startupInfo = new STARTUPINFO();
            startupInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));

            PROCESS_INFORMATION pi;
            if (!_CreateProcess(
                lpApplicationName,
                lpCommandLine,
                lpProcessAttributes,
                lpThreadAttributes,
                bInheritHandles,
                dwCreationFlags,
                lpEnvironment,
                lpCurrentDirectory,
                ref startupInfo,
                out pi))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
            return pi;
        }
Esempio n. 6
0
        public static Debuggee Launch(string executable,
			string argumentString = null, string workingDirectory = null)
        {
            var si = new STARTUPINFO {
                cb = Marshal.SizeOf(typeof(STARTUPINFO)),
            };
            var pi = new PROCESS_INFORMATION();

            if (argumentString == string.Empty)
                argumentString = null;
            if (workingDirectory == string.Empty)
                workingDirectory = null;

            if (!API.CreateProcess(executable, argumentString, IntPtr.Zero, IntPtr.Zero, true,
                ProcessCreationFlags.CreateNewConsole | // Create extra console for the process
                ProcessCreationFlags.DebugOnlyThisProcess // Grant debugger access to the process
                ,IntPtr.Zero, workingDirectory, ref si, out pi))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            var dbg = new Debuggee(executable,
                pi.hProcess, pi.dwProcessId,
                pi.hThread, pi.dwThreadId,
                ExecutableMetaInfo.ExtractFrom(executable));

            return dbg;
        }
        public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true)
        {
            var hUserToken = IntPtr.Zero;
            var startInfo = new STARTUPINFO();
            var procInfo = new PROCESS_INFORMATION();
            var pEnv = IntPtr.Zero;
            int iResultOfCreateProcessAsUser;

            startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));

            try
            {
                if (!GetSessionUserToken(ref hUserToken))
                {
                    throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed.");
                }

                uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
                startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
                startInfo.lpDesktop = "winsta0\\default";

                if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
                {
                    throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
                }

                if (!CreateProcessAsUser(hUserToken,
                    appPath, // Application Name
                    cmdLine, // Command Line
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    dwCreationFlags,
                    pEnv,
                    workDir, // Working directory
                    ref startInfo,
                    out procInfo))
                {
                    throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.\n");
                }

                iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
            }
            finally
            {
                CloseHandle(hUserToken);
                if (pEnv != IntPtr.Zero)
                {
                    DestroyEnvironmentBlock(pEnv);
                }
                CloseHandle(procInfo.hThread);
                CloseHandle(procInfo.hProcess);
            }

            return true;
        }
Esempio n. 8
0
 public static extern bool CreateProcess(String imageName,
     String cmdLine,
     IntPtr lpProcessAttributes,
     IntPtr lpThreadAttributes,
     bool boolInheritHandles,
     uint dwCreationFlags,
     IntPtr lpEnvironment,
     String lpszCurrentDir,
     ref STARTUPINFO si,
     out PROCESS_INFORMATION pi);
Esempio n. 9
0
 public static extern bool CreateProcess(StringBuilder lpApplicationName, StringBuilder lpCommandLine,
     SECURITY_ATTRIBUTES lpProcessAttributes,
     SECURITY_ATTRIBUTES lpThreadAttributes,
     bool bInheritHandles,
     int dwCreationFlags,
     StringBuilder lpEnvironment,
     StringBuilder lpCurrentDirectory,
     ref STARTUPINFO lpStartupInfo,
     ref PROCESS_INFORMATION lpProcessInformation
     );
 internal static extern bool CreateProcessWithLogonW(
     string userName,
     string domain,
     string passwordInClearText,
     LogonFlags logonFlags,
     [MarshalAs(UnmanagedType.LPTStr)] string appName,
     StringBuilder cmdLine,
     int creationFlags,
     IntPtr environmentBlock,
     [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory,
     STARTUPINFO lpStartupInfo,
     PROCESS_INFORMATION lpProcessInformation);
Esempio n. 11
0
 public static extern bool CreateProcessAsUser(
 IntPtr hToken,
 string lpApplicationName,
 string lpCommandLine,
 ref SECURITY_ATTRIBUTES lpProcessAttributes,
 ref SECURITY_ATTRIBUTES lpThreadAttributes,
 bool bInheritHandles,
 uint dwCreationFlags,
 IntPtr lpEnvironment,
 string lpCurrentDirectory,
 ref STARTUPINFO lpStartupInfo,
 out PROCESS_INFORMATION lpProcessInformation);
Esempio n. 12
0
 internal static extern bool CreateProcess(
     [MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName,
     StringBuilder lpCommandLine,
     ref SECURITY_ATTRIBUTES procSecAttrs,
     ref SECURITY_ATTRIBUTES threadSecAttrs,
     bool bInheritHandles,
     int dwCreationFlags,
     IntPtr lpEnvironment,
     [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory,
     STARTUPINFO lpStartupInfo,
     PROCESS_INFORMATION lpProcessInformation
 );
Esempio n. 13
0
        private string RunProcess(string id, string command)
        {
            try {
                IntPtr dupedToken = new IntPtr(0);

                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.bInheritHandle = false;
                sa.Length = Marshal.SizeOf(sa);
                sa.lpSecurityDescriptor = (IntPtr)0;

                var token = WindowsIdentity.GetCurrent().Token;

                const uint GENERIC_ALL = 0x10000000;

                const int SecurityImpersonation = 2;
                const int TokenType = 1;

                var ret = DuplicateTokenEx(token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref dupedToken);
                if (ret == false)
                    throw new Exception("DuplicateTokenEx failed (" + Marshal.GetLastWin32Error() + ")");

                STARTUPINFO si = new STARTUPINFO();
                si.cb = Marshal.SizeOf(si);
                si.lpDesktop = "";
                PROCESS_INFORMATION pi = new PROCESS_INFORMATION();

                uint exitCode;
                try {
                    ret = CreateProcessAsUser(dupedToken, null, @"c:\windows\system32\shutdown.exe " + command + " /m " + id, ref sa, ref sa, false, 0, (IntPtr)0, "c:\\", ref si, out pi);

                    if (ret == false)
                        throw new Exception("CreateProcessAsUser failed (" + Marshal.GetLastWin32Error() + ")");

                    WaitForSingleObject(pi.hProcess, 10000);
                    GetExitCodeProcess(pi.hProcess, out exitCode);
                }
                catch (Exception ex) {
                    throw ex;
                }
                finally {
                    CloseHandle(pi.hProcess);
                    CloseHandle(pi.hThread);
                    CloseHandle(dupedToken);
                }

                if (exitCode == 0)
                    return "";
                return "Exit code: " + exitCode;
            }
            catch (Exception ex) {
                return ex.Message;
            }
        }
 public static extern Boolean CreateProcessWithLogonW(
     String lpszUsername,
     String lpszDomain,
     String lpszPassword,
     Int32 dwLogonFlags,
     String applicationName,
     String commandLine,
     Int32 creationFlags,
     IntPtr environment,
     String currentDirectory,
     ref STARTUPINFO sui,
     out PROCESS_INFORMATION processInfo
     );
 public static extern Boolean CreateProcessAsUser(
     IntPtr hToken,
     String lpApplicationName,
     String lpCommandLine,
     IntPtr lpProcessAttributes,
     IntPtr lpThreadAttributes,
     Boolean bInheritHandles,
     Int32 dwCreationFlags,
     IntPtr lpEnvironment,
     String lpCurrentDirectory,
     ref STARTUPINFO lpStartupInfo,
     out PROCESS_INFORMATION lpProcessInformation
     );
Esempio n. 16
0
        static int Main(string[] args)
        {
            var exe = Assembly.GetExecutingAssembly().Location;
            var dir = Path.GetDirectoryName(exe);
            var name = Path.GetFileNameWithoutExtension(exe);

            var configPath = Path.Combine(dir, name + ".shim");
            if(!File.Exists(configPath)) {
                Console.Error.WriteLine("Couldn't find " + Path.GetFileName(configPath) + " in " + dir);
                return 1;
            }

            var config = Config(configPath);
            var path = Get(config, "path");
            var add_args = Get(config, "args");

            var si = new STARTUPINFO();
            var pi = new PROCESS_INFORMATION();

            // create command line
            var cmd_args = add_args ?? "";
            var pass_args = Serialize(args);
            if(!string.IsNullOrEmpty(pass_args)) {
                if(!string.IsNullOrEmpty(cmd_args)) cmd_args += " ";
                cmd_args += pass_args;
            }
            if(!string.IsNullOrEmpty(cmd_args)) cmd_args = " " + cmd_args;
            var cmd = "\"" + path + "\"" + cmd_args;

            if(!CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero,
                bInheritHandles: true,
                dwCreationFlags: 0,
                lpEnvironment: IntPtr.Zero, // inherit parent
                lpCurrentDirectory: null, // inherit parent
                lpStartupInfo: ref si,
                lpProcessInformation: out pi)) {

                return Marshal.GetLastWin32Error();
            }

            WaitForSingleObject(pi.hProcess, INFINITE);

            uint exit_code = 0;
            GetExitCodeProcess(pi.hProcess, out exit_code);

            // Close process and thread handles.
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);

            return (int)exit_code;
        }
Esempio n. 17
0
 private static extern bool CreateProcess(
     [MarshalAs(UnmanagedType.LPTStr)]
     string lpApplicationName,
     string lpCommandLine,
     IntPtr lpProcessAttributes,
     IntPtr lpThreadAttributes,
     bool bInheritHandles,
     int dwCreationFlags,
     IntPtr lpEnvironment,
     [MarshalAs(UnmanagedType.LPTStr)]
     string lpCurrentDirectory,
     STARTUPINFO lpStartupInfo,
     ref PROCESS_INFORMATION lpProcessInformation
 );
Esempio n. 18
0
        public override object Execute()
        {
            object result = null;

            if (!this.HasRun)
            {
                Process process = null;
                STARTUPINFO startupInfo = new STARTUPINFO();
                PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();

                Context.AnalysisOut.PersistVariables();

                switch (option)
                {
                    case CommandNames.DISPLAY:

                        bool created = CreateProcess(
                            null,
                            commandlineString,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            false,
                            0,
                            IntPtr.Zero,
                            null,
                            ref startupInfo,
                            out processInfo);

                        if (created)
                        {
                            process = Process.GetProcessById((int)processInfo.dwProcessId);
                        }
                        else
                        {
                            throw new GeneralException("Could not execute the command: '" + commandlineString + "'");
                        }
                        break;

                    case CommandNames.TO:
                        break;

                    case "PRINT":
                        break;
                }
                this.HasRun = true;
            }
            return result;
        }
Esempio n. 19
0
 public DLLInformation inject(string exePath, string dllPath)
 {
     DLLInformation d = new DLLInformation();
     STARTUPINFO lpStartupInfo = new STARTUPINFO();
     PROCESS_INFORMATION lpProcessInfo = new PROCESS_INFORMATION();
     SECURITY_ATTRIBUTES lpSecurityAttributes1 = new SECURITY_ATTRIBUTES();
     SECURITY_ATTRIBUTES lpSecurityAttributes2 = new SECURITY_ATTRIBUTES();
     lpSecurityAttributes1.nLength = Marshal.SizeOf(lpSecurityAttributes1);
     lpSecurityAttributes2.nLength = Marshal.SizeOf(lpSecurityAttributes2);
     IntPtr hProcess;
     CreateProcess(exePath, "", ref lpSecurityAttributes1, ref lpSecurityAttributes2, false, 0x0020, IntPtr.Zero, null, ref lpStartupInfo, out lpProcessInfo);
     hProcess = OpenProcess((int)(0x000F0000L | 0x00100000L | 0xFFF), false, lpProcessInfo.dwProcessId);
     d.ProcID = lpProcessInfo.dwProcessId;
     d.ErrorCode = commonInject(hProcess, dllPath, ref d);
     return d;
 }
Esempio n. 20
0
        /// Launch a batch file.
        /// This function calls CreateProcess directly, and ensures that 
        /// bInheritHandles=false, which prevents handle leakage into 
        /// child processes.
        public static QRProcess LaunchBatchFile(
            string batchFilePath, 
            string workingDir,
            bool unicode, 
            string extraCmdCommandLine)
        {
            string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
            string cmdPath = Path.Combine(systemPath, "cmd.exe");

            StringBuilder commandline = new StringBuilder();
            if (unicode) {
                commandline.Append("/U ");
            }
            commandline.Append("/C "); // terminate after executing
            commandline.AppendFormat("\"{0} {1}\" ",
                batchFilePath,
                String.IsNullOrEmpty(extraCmdCommandLine) ? "" : extraCmdCommandLine);

            uint dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS;

            STARTUPINFO startupInfo = new STARTUPINFO();
            startupInfo.cb = Marshal.SizeOf(startupInfo);
            startupInfo.dwFlags = STARTF_USESHOWWINDOW;
            startupInfo.wShowWindow = SW_HIDE;

            PROCESS_INFORMATION processInfo;

            bool success = CreateProcess(
                cmdPath,
                commandline,
                null,
                null,
                /* bInheritHandles */ false,
                dwCreationFlags,
                IntPtr.Zero,
                workingDir,
                ref startupInfo,
                out processInfo);
            if (!success) {
                int gle = Marshal.GetLastWin32Error();
                return null;
            }

            QRProcess process = new QRProcess(processInfo);
            return process;
        }
Esempio n. 21
0
        //Initialization
        //        static uint SW_SHOW = 5;
        public static PROCESS_INFORMATION CreateProc(string fullCommand)
        {
            STARTUPINFO si = new STARTUPINFO();
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            CreateProcess(
                null,
                fullCommand,
                IntPtr.Zero,
                IntPtr.Zero,
                false,
                0,
                IntPtr.Zero,
                null,
                ref si,
                out pi);

            return pi;
        }
Esempio n. 22
0
        public static void Run(out String status, out String identity, String cmdline, String startfrom)
        {
            bool      ret = false;

            identity = CurrentUserName;

            SECURITY_ATTRIBUTES sa  = new SECURITY_ATTRIBUTES();
            sa.bInheritHandle       = false;
            sa.Length               = Marshal.SizeOf(sa);
            sa.lpSecurityDescriptor = (IntPtr)0;

            STARTUPINFO si          = new STARTUPINFO();
            si.cb                   = Marshal.SizeOf(si);
            si.lpDesktop            = "";

            string commandLinePath;
            commandLinePath = cmdline;

            PROCESS_INFORMATION pi  = new PROCESS_INFORMATION();
            ret = CreateProcess(
                null,			//LPCTSTR lpApplicationName,
                cmdline,		//LPTSTR lpCommandLine,
                ref sa,			//LPSECURITY_ATTRIBUTES lpProcessAttributes,
                ref sa,			//LPSECURITY_ATTRIBUTES lpThreadAttributes,
                false,			//BOOL bInheritHandles,
                0,				//DWORD dwCreationFlags,
                (IntPtr)0,		//LPVOID lpEnvironment,
                startfrom,		//LPCTSTR lpCurrentDirectory,
                ref si,			//LPSTARTUPINFO lpStartupInfo,
                out pi);		//LPPROCESS_INFORMATION lpProcessInformation

            if (ret == false)
            {
                status = "CreateProcess failed with " + Marshal.GetLastWin32Error();
            }
            else
            {
                status = "CreateProcess SUCCESS.  The child PID is" + pi.dwProcessId;

                CloseHandle(pi.hProcess);
                CloseHandle(pi.hThread);
            }
        }
Esempio n. 23
0
        public static bool Run(string target,string parm)
        {
            STARTUPINFO sInfo = new STARTUPINFO();
            SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
            SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
            pSec.nLength = Marshal.SizeOf(pSec);
            tSec.nLength = Marshal.SizeOf(tSec);

            return CreateProcess(new StringBuilder(target),
                          new StringBuilder(parm),
                          null,
                          null,
                          false,
                          0x00000004,
                          null,
                          null,
                          ref sInfo,
                          ref pInfo);
        }
        public static void LaunchCommand1(string strCommand, string strDomain, string strName, string strPassword)
        {
            // Variables
            PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();
            STARTUPINFO startInfo = new STARTUPINFO();
            bool bResult = false;
            UInt32 uiResultWait = WAIT_FAILED;

            try
            {
                // Create process
                startInfo.cb = Marshal.SizeOf(startInfo);

                bResult = CreateProcessWithLogonW(
                    strName,
                    strDomain,
                    strPassword,
                    0,
                    null,
                    strCommand,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out processInfo
                );
                if (!bResult) { throw new Exception("CreateProcessWithLogonW error #" + Marshal.GetLastWin32Error().ToString()); }

                // Wait for process to end
                uiResultWait = WaitForSingleObject(processInfo.hProcess, INFINITE);
                if (uiResultWait == WAIT_FAILED) { throw new Exception("WaitForSingleObject error #" + Marshal.GetLastWin32Error()); }

            }
            finally
            {
                // Close all handles
                CloseHandle(processInfo.hProcess);
                CloseHandle(processInfo.hThread);
            }
        }
Esempio n. 25
0
    public static void CreateLinProcess(string lineagefolder, long ip, ushort port, string s3ep1, string logindll)
    {
        //"C:\\Lineage Tikal\\S3EP1.exe"
        //"2130706433 16600"
        //3325717308
        var binpath = System.IO.Path.Combine(lineagefolder, s3ep1);

        STARTUPINFO si = new STARTUPINFO();
        PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
        bool success = CreateProcess(binpath, string.Format("\"{0}\" {1} {2}", binpath, ip, port),
            IntPtr.Zero, IntPtr.Zero, false,
            ProcessCreationFlags.CREATE_SUSPENDED | ProcessCreationFlags.CREATE_DEFAULT_ERROR_MODE,
            IntPtr.Zero, null, ref si, out pi);

        var logindllpath = System.IO.Path.Combine(lineagefolder, logindll);
        DllInjector.GetInstance.bInject(pi.dwProcessId, logindllpath);
        System.Threading.Thread.Sleep(1000);
        //System.Windows.Forms.MessageBox.Show("Attach debugger");

        IntPtr t_handle = pi.hThread;
        ResumeThread(t_handle);
    }
 public int CreateProcessAsUser(string app, string cmd)
 {
     PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
     try {
         SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
         sa.Length = Marshal.SizeOf(sa);
         STARTUPINFO si = new STARTUPINFO();
         si.cb = Marshal.SizeOf(si);
         si.lpDesktop = String.Empty;
         if (app != null && app.Length == 0)
             app = null;
         if (cmd != null && cmd.Length == 0)
             cmd = null;
         if (!Win32API.CreateProcessAsUser(
         _userTokenHandle,
         app,
         cmd,
         ref sa, ref sa,
         false, 0, IntPtr.Zero,
         @"C:\", ref si, ref pi
         )) {
             int error = Marshal.GetLastWin32Error();
             Win32Exception ex = new Win32Exception(error);
             string message = String.Format("CreateProcessAsUser Error: {0}", ex.Message);
             throw new ApplicationException(message, ex);
         }
     } catch (Exception ex) {
         EventLog.WriteEntry("Screen Monitor", ex.Message, EventLogEntryType.Error, 1, 1);
         throw;
     } finally {
         if (pi.hProcess != IntPtr.Zero)
             Win32API.CloseHandle(pi.hProcess);
         if (pi.hThread != IntPtr.Zero)
             Win32API.CloseHandle(pi.hThread);
     }
     return pi.dwProcessID;
 }
Esempio n. 27
0
        public static ExternalProcess Create(string command)
        {
            PROCESS_INFORMATION process_info = new PROCESS_INFORMATION();
            STARTUPINFO startup_info = new STARTUPINFO();

            startup_info.cb = Marshal.SizeOf(startup_info);
            startup_info.dwFlags = STARTF_USESTDHANDLES;

            SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
            SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();

            bool result = CreateProcess(null, command, ref pSec, ref tSec, true,
                DETACHED_PROCESS, IntPtr.Zero, null, ref startup_info, out process_info);

            int process_id = process_info.dwProcessId;

            if (!result)
            {
                Console.Error.WriteLine("CreateProcess failed");
                return null;
            }

            return new ExternalProcess((uint)process_id);
        }
Esempio n. 28
0
        public static int? StartProcessSuspended(string fileName, string args)
        {
            const uint CREATE_SUSPENDED = 0x00000004;

            var pInfo = new PROCESS_INFORMATION();
            var sInfo = new STARTUPINFO();
            var pSec = new SECURITY_ATTRIBUTES();
            var tSec = new SECURITY_ATTRIBUTES();
            pSec.nLength = Marshal.SizeOf(pSec);
            tSec.nLength = Marshal.SizeOf(tSec);

            var result = CreateProcess(
                null,
                fileName + " " + args,
                ref pSec,
                ref tSec,
                false,
                CREATE_SUSPENDED,
                IntPtr.Zero,
                null,
                ref sInfo,
                out pInfo);
            return result ? (int?)pInfo.dwProcessId : null;
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            string program     = "c:\\windows\\system32\\cmd.exe";
            string programArgs = "";
            bool   showHelp    = false;
            bool   bypass      = false;

            Console.WriteLine(
                "SharpBlock by @_EthicalChaos_\n" +
                $"  DLL Blocking app for child processes { (IntPtr.Size == 8 ? "x86_64" : "x86")} \n"
                );

            OptionSet option_set = new OptionSet()
                                   .Add("e=|exe=", "Program to execute (default cmd.exe)", v => program      = v)
                                   .Add("a=|args=", "Arguments for program (default null)", v => programArgs = v)
                                   .Add("n=|name=", "Name of DLL to block", v => blockDllName.Add(v))
                                   .Add("c=|copyright=", "Copyright string to block", v => blockCopyright.Add(v))
                                   .Add("p=|product=", "Product string to block", v => blockProduct.Add(v))
                                   .Add("d=|description=", "Description string to block", v => blockDescription.Add(v))
                                   .Add("b=|bypass="******"Bypasses AMSI within the executed process (true|false)", v => bypass = v != null)
                                   .Add("h|help", "Display this help", v => showHelp = v != null);

            try {
                option_set.Parse(args);

                if (showHelp)
                {
                    option_set.WriteOptionDescriptions(Console.Out);
                    return;
                }
            } catch (Exception e) {
                Console.WriteLine("[!] Failed to parse arguments: {0}", e.Message);
                option_set.WriteOptionDescriptions(Console.Out);
                return;
            }

            IntPtr amsiBase = WinAPI.LoadLibrary("amsi.dll");

            amsiInitalizePtr = WinAPI.GetProcAddress(amsiBase, "AmsiInitialize");

            Console.WriteLine($"[+] in-proc AMSI 0x{amsiBase:8x}");

            STARTUPINFO startupInfo = new STARTUPINFO();

            startupInfo.cb = (uint)Marshal.SizeOf(startupInfo);
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();

            if (!CreateProcess(program, $"\"{program}\" {programArgs}", IntPtr.Zero, IntPtr.Zero, true, WinAPI.DEBUG_PROCESS, IntPtr.Zero, null,
                               ref startupInfo, out pi))
            {
                Console.WriteLine($"[!] Failed to create process {program}");
                return;
            }

            Console.WriteLine($"[+] Launched process {program} with PID {pi.dwProcessId}");

            bool bContinueDebugging = true;
            Dictionary <uint, IntPtr> processHandles = new Dictionary <uint, IntPtr>();
            Dictionary <uint, IntPtr> threadHandles  = new Dictionary <uint, IntPtr>();

            while (bContinueDebugging)
            {
                IntPtr debugEventPtr        = Marshal.AllocHGlobal(1024);
                bool   bb                   = WinAPI.WaitForDebugEvent(debugEventPtr, 1000);
                UInt32 dwContinueDebugEvent = WinAPI.DBG_CONTINUE;
                if (bb)
                {
                    WinAPI.DEBUG_EVENT DebugEvent   = (WinAPI.DEBUG_EVENT)Marshal.PtrToStructure(debugEventPtr, typeof(WinAPI.DEBUG_EVENT));
                    IntPtr             debugInfoPtr = GetIntPtrFromByteArray(DebugEvent.u);
                    switch (DebugEvent.dwDebugEventCode)
                    {
                    case WinAPI.CREATE_PROCESS_DEBUG_EVENT:
                        WinAPI.CREATE_PROCESS_DEBUG_INFO CreateProcessDebugInfo = (WinAPI.CREATE_PROCESS_DEBUG_INFO)Marshal.PtrToStructure(debugInfoPtr, typeof(WinAPI.CREATE_PROCESS_DEBUG_INFO));
                        processHandles[DebugEvent.dwProcessId] = CreateProcessDebugInfo.hProcess;
                        threadHandles[DebugEvent.dwThreadId]   = CreateProcessDebugInfo.hThread;

                        if (bypass)
                        {
                            SetHardwareBreakpoint(CreateProcessDebugInfo.hThread, amsiInitalizePtr);
                        }

                        break;

                    case WinAPI.CREATE_THREAD_DEBUG_EVENT:
                        WinAPI.CREATE_THREAD_DEBUG_INFO CreateThreadDebugInfo = (WinAPI.CREATE_THREAD_DEBUG_INFO)Marshal.PtrToStructure(debugInfoPtr, typeof(WinAPI.CREATE_THREAD_DEBUG_INFO));
                        threadHandles[DebugEvent.dwThreadId] = CreateThreadDebugInfo.hThread;

                        if (bypass)
                        {
                            SetHardwareBreakpoint(CreateThreadDebugInfo.hThread, amsiInitalizePtr);
                        }

                        break;

                    case WinAPI.EXIT_PROCESS_DEBUG_EVENT:
                        if (pi.dwProcessId == DebugEvent.dwProcessId)
                        {
                            bContinueDebugging = false;
                        }
                        break;

                    case WinAPI.LOAD_DLL_DEBUG_EVENT:
                        WinAPI.LOAD_DLL_DEBUG_INFO LoadDLLDebugInfo = (WinAPI.LOAD_DLL_DEBUG_INFO)Marshal.PtrToStructure(debugInfoPtr, typeof(WinAPI.LOAD_DLL_DEBUG_INFO));
                        string dllPath = PatchEntryPointIfNeeded(LoadDLLDebugInfo.hFile, LoadDLLDebugInfo.lpBaseOfDll, processHandles[DebugEvent.dwProcessId]);
                        break;

                    case WinAPI.EXCEPTION_DEBUG_EVENT:
                        WinAPI.EXCEPTION_DEBUG_INFO ExceptionDebugInfo = (WinAPI.EXCEPTION_DEBUG_INFO)Marshal.PtrToStructure(debugInfoPtr, typeof(WinAPI.EXCEPTION_DEBUG_INFO));

                        if (ExceptionDebugInfo.ExceptionRecord.ExceptionCode == WinAPI.EXCEPTION_SINGLE_STEP)
                        {
                            //Check to see if the single step breakpoint is at AmsiInitalize
                            if (ExceptionDebugInfo.ExceptionRecord.ExceptionAddress == amsiInitalizePtr)
                            {
                                //It is, to update the thread context to return to caller with
                                //an invalid result
                                DisableAMSI(threadHandles[DebugEvent.dwThreadId], processHandles[DebugEvent.dwProcessId]);
                                //Opsec purposes, lets now clear all threads of hardware breakpoints
                                ClearHardwareBreakpoints(threadHandles.Values.ToArray());
                            }
                        }
                        else
                        {
                            dwContinueDebugEvent = WinAPI.DBG_EXCEPTION_NOT_HANDLED;
                        }

                        break;
                    }

                    WinAPI.ContinueDebugEvent((uint)DebugEvent.dwProcessId,
                                              (uint)DebugEvent.dwThreadId,
                                              dwContinueDebugEvent);
                }
                if (debugEventPtr != null)
                {
                    Marshal.FreeHGlobal(debugEventPtr);
                }
            }

            int exitCode;

            WinAPI.GetExitCodeProcess(pi.hProcess, out exitCode);
            Console.WriteLine($"[+] Process {program} with PID {pi.dwProcessId} exited wit code {exitCode}");
        }
Esempio n. 30
0
        public static int CreateProcessAsUser(int sessionId, string filename, string arguments)
        {
            int    processId = 0;
            IntPtr hToken    = IntPtr.Zero;

            try
            {
                if (WTSQueryUserToken(sessionId, out hToken))
                {
                    string cmdLine          = string.Format("{0} {1}", filename, arguments);
                    SECURITY_ATTRIBUTES sap = new SECURITY_ATTRIBUTES();
                    SECURITY_ATTRIBUTES sat = new SECURITY_ATTRIBUTES();
                    STARTUPINFO         si  = new STARTUPINFO();
                    sap.Length   = Marshal.SizeOf(sap);
                    sat.Length   = Marshal.SizeOf(sat);
                    si.cb        = Marshal.SizeOf(si);
                    si.lpDesktop = @"WinSta0\Default";

                    PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
                    if (CreateProcessAsUser(hToken, null, cmdLine, ref sap, ref sat, false, 0, IntPtr.Zero, null, ref si, out pi))
                    {
                        if (pi.hProcess != null)
                        {
                            CloseHandle(pi.hProcess);
                        }
                        if (pi.hThread != null)
                        {
                            CloseHandle(pi.hThread);
                        }
                        processId = (int)pi.dwProcessId;
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error())
                              {
                                  Source = "CreateProcessAsUser"
                              };
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error())
                          {
                              Source = "WTSQueryUserToken"
                          };
                }
            }
            catch (Win32Exception ex)
            {
                TraceLog.WriteLineError(string.Format(">>>Win32Exception: ErrorCode={0}, Message={1}, Source={2}, time={3:o}",
                                                      ex.NativeErrorCode, ex.Message, ex.Source, DateTime.Now));
                throw;
            }
            catch (Exception ex) { TraceLog.WriteException(ex); throw; }
            finally
            {
                if (hToken != IntPtr.Zero)
                {
                    CloseHandle(hToken);
                }
            }
            return(processId);
        }
            // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
            private static void CreatePipProcess(IMineContext mineContext, string cmdLine)
            {
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES();
                IntPtr hReadOut, hWriteOut;

                //set the bInheritHandle flag so pipe handles are inherited

                saAttr.bInheritHandle       = true;
                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                saAttr.length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                //get handle to current stdOut

                bool bret;

                IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

                Marshal.StructureToPtr(saAttr, mypointer, true);
                bret = CreatePipe(out hReadOut, out hWriteOut, mypointer, 0);
                //ensure the read handle to pipe for stdout is not inherited
                SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0);
                ////Create pipe for the child process's STDIN
                STARTUPINFO lpStartupInfo = new STARTUPINFO {
                    cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                    dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                    wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                    hStdOutput  = hWriteOut,
                    hStdError   = hWriteOut,
                    hStdInput   = IntPtr.Zero
                };
                PROCESS_INFORMATION lpProcessInformation;

                if (CreateProcess(
                        lpApplicationName: null,
                        lpCommandLine: new StringBuilder(cmdLine),
                        lpProcessAttributes: IntPtr.Zero,
                        lpThreadAttributes: IntPtr.Zero,
                        bInheritHandles: true,
                        dwCreationFlags: NORMAL_PRIORITY_CLASS,
                        lpEnvironment: IntPtr.Zero,
                        lpCurrentDirectory: null,
                        lpStartupInfo: ref lpStartupInfo,
                        lpProcessInformation: out lpProcessInformation))
                {
                    if (bret == false)
                    {
                        int lasterr = Marshal.GetLastWin32Error();
                    }
                    else
                    {
                        Bus.DelegateHandler <MineStopedEvent> closeHandle = null;
                        bool isHWriteOutHasClosed = false;
                        Daemon(mineContext, () => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            Global.UnAccess(closeHandle);
                        });
                        closeHandle = Global.Access <MineStopedEvent>(
                            Guid.Parse("91642027-fd28-4bdd-a05a-31caac6609b1"),
                            "挖矿停止后关闭非托管的日志句柄",
                            LogEnum.Log,
                            action: message => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            Global.UnAccess(closeHandle);
                        });
                        string pipLogFileFullName = Path.Combine(SpecialPath.LogsDirFullName, mineContext.PipeFileName);
                        Task.Factory.StartNew(() => {
                            using (FileStream fs = new FileStream(pipLogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                                using (StreamReader sr = new StreamReader(fs)) {
                                    byte[] buffer = new byte[1024];
                                    int ret;
                                    // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                                    while ((ret = Read(buffer, 0, buffer.Length, hReadOut)) > 0)
                                    {
                                        fs.Write(buffer, 0, ret);
                                        if (buffer[ret - 1] == '\r' || buffer[ret - 1] == '\n')
                                        {
                                            fs.Flush();
                                        }
                                    }
                                }
                            CloseHandle(hReadOut);
                        });
                        Task.Factory.StartNew(() => {
                            ReadPrintLoopLogFile(mineContext, pipLogFileFullName);
                        });
                    }
                }
                else
                {
                    Global.WriteLine("内核启动失败,请重试", ConsoleColor.Red);
                }
            }
Esempio n. 32
0
        public static string ExecuteCommand(string command)
        {
            string output = "";

            if (TokenManager.Token == IntPtr.Zero && TokenManager.Method == 0)
            {
                Process          process   = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                startInfo.FileName               = @"C:\windows\system32\cmd.exe";
                startInfo.Arguments              = "/C" + command + " && exit";
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError  = true;
                startInfo.UseShellExecute        = false;
                process.StartInfo = startInfo;
                process.Start();
                output = process.StandardOutput.ReadToEnd();
                if (output == "")
                {
                    output = string.Concat("ERR:", process.StandardError.ReadToEnd());
                }
                process.WaitForExit();
                process.Close();
            }
            else
            {
                IntPtr out_read  = IntPtr.Zero;
                IntPtr out_write = IntPtr.Zero;

                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES();
                saAttr.nLength              = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
                saAttr.bInheritHandle       = true;
                saAttr.lpSecurityDescriptor = IntPtr.Zero;

                CreatePipe(ref out_read, ref out_write, ref saAttr, 0);

                STARTUPINFO startupInfo = new STARTUPINFO();
                startupInfo.cb          = Marshal.SizeOf(startupInfo);
                startupInfo.lpDesktop   = "";
                startupInfo.hStdOutput  = out_write;
                startupInfo.hStdError   = out_write;
                startupInfo.wShowWindow = 0;
                startupInfo.dwFlags    |= 0x00000101;

                PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION();
                LogonFlags          l           = new LogonFlags();

                if (TokenManager.Method == 1)
                {
                    CreateProcessAsUserW(TokenManager.Token, @"c:\windows\system32\cmd.exe /Q /C" + @command, null, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startupInfo, out processInfo);
                }

                else if (TokenManager.Method == 2)
                {
                    CreateProcessWithTokenW(TokenManager.Token, l, null, @"c:\windows\system32\cmd.exe /Q /C" + @command, 0, IntPtr.Zero, null, ref startupInfo, out processInfo);
                }

                else
                {
                    CreateProcessWithLogonW(TokenManager.creds[0], TokenManager.creds[1], TokenManager.creds[2], l, null, @"c:\windows\system32\cmd.exe /Q /C" + command, 0, 0, null, ref startupInfo, out processInfo);
                }


                byte[] buf    = new byte[100];
                int    dwRead = 0;
                Thread.Sleep(500);

                while (true)
                {
                    bool bSuccess = ReadFile(out_read, buf, 100, ref dwRead, IntPtr.Zero);
                    output = string.Concat(output, Encoding.Default.GetString(buf));

                    if (!bSuccess || dwRead < 100)
                    {
                        break;
                    }
                }

                CloseHandle(out_read);
                CloseHandle(out_write);
            }

            return(output);
        }
            // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
            private static void CreatePipProcess(IMineContext mineContext, string kernelExeFileFullName, string arguments)
            {
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES
                {
                    bInheritHandle       = true,
                    lpSecurityDescriptor = IntPtr.Zero,
                    length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES))
                };

                //set the bInheritHandle flag so pipe handles are inherited

                saAttr.lpSecurityDescriptor = IntPtr.Zero;
                //get handle to current stdOut

                IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

                Marshal.StructureToPtr(saAttr, mypointer, true);
                var bret = CreatePipe(out var hReadOut, out var hWriteOut, mypointer, 0);

                //ensure the read handle to pipe for stdout is not inherited
                SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0);
                ////Create pipe for the child process's STDIN
                STARTUPINFO lpStartupInfo = new STARTUPINFO {
                    cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                    dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                    wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                    hStdOutput  = hWriteOut,
                    hStdError   = hWriteOut,
                    hStdInput   = IntPtr.Zero
                };
                string cmdLine = $"\"{kernelExeFileFullName}\" {arguments}";

                Logger.InfoDebugLine(cmdLine);
                StringBuilder lpEnvironment = new StringBuilder();
                // 复制父进程的环境变量
                IDictionary dic = Environment.GetEnvironmentVariables();

                // 追加环境变量
                foreach (var item in mineContext.CoinKernel.EnvironmentVariables)
                {
                    dic.Add(item.Key, item.Value);
                }
                foreach (var key in dic.Keys)
                {
                    if (key == null || key.ToString().Contains("\0"))
                    {
                        continue;
                    }
                    var value = dic[key];
                    if (value == null || value.ToString().Contains("\0"))
                    {
                        continue;
                    }
                    lpEnvironment.Append($"{key.ToString()}={value.ToString()}\0");
                }
                if (CreateProcess(
                        lpApplicationName: null,
                        lpCommandLine: new StringBuilder(cmdLine),
                        lpProcessAttributes: IntPtr.Zero,
                        lpThreadAttributes: IntPtr.Zero,
                        bInheritHandles: true,
                        dwCreationFlags: NORMAL_PRIORITY_CLASS,
                        lpEnvironment: lpEnvironment,
                        lpCurrentDirectory: Path.GetDirectoryName(kernelExeFileFullName),
                        lpStartupInfo: ref lpStartupInfo,
                        lpProcessInformation: out _))
                {
                    if (bret == false)
                    {
                        int lasterr = Marshal.GetLastWin32Error();
                        VirtualRoot.Happened(new StartingMineFailedEvent($"管道型进程创建失败 lasterr:{lasterr}"));
                    }
                    else
                    {
                        Bus.DelegateHandler <MineStopedEvent> closeHandle = null;
                        bool isHWriteOutHasClosed = false;
                        Daemon(mineContext, () => {
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            VirtualRoot.UnPath(closeHandle);
                        });
                        closeHandle = VirtualRoot.On <MineStopedEvent>("挖矿停止后关闭非托管的日志句柄", LogEnum.DevConsole,
                                                                       action: message => {
                            // 挖矿停止后摘除挖矿内核进程守护器
                            if (_sDaemon != null)
                            {
                                VirtualRoot.UnPath(_sDaemon);
                                _sDaemon = null;
                            }
                            if (!isHWriteOutHasClosed)
                            {
                                CloseHandle(hWriteOut);
                                isHWriteOutHasClosed = true;
                            }
                            VirtualRoot.UnPath(closeHandle);
                        });
                        string pipLogFileFullName = Path.Combine(SpecialPath.LogsDirFullName, mineContext.PipeFileName);
                        Task.Factory.StartNew(() => {
                            FileStream fs = new FileStream(pipLogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            using (StreamReader sr = new StreamReader(fs)) {
                                byte[] buffer = new byte[1024];
                                int ret;
                                // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                                while ((ret = Read(buffer, 0, buffer.Length, hReadOut)) > 0)
                                {
                                    fs.Write(buffer, 0, ret);
                                    if (buffer[ret - 1] == '\r' || buffer[ret - 1] == '\n')
                                    {
                                        fs.Flush();
                                    }
                                }
                            }
                            CloseHandle(hReadOut);
                        });
                        ReadPrintLoopLogFileAsync(mineContext, pipLogFileFullName);
                    }
                }
                else
                {
                    VirtualRoot.Happened(new StartingMineFailedEvent($"内核启动失败,请重试"));
                }
            }
Esempio n. 34
0
        /// <summary>
        ///     Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt
        /// </summary>
        /// <param name="applicationName">The name of the application to launch</param>
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>
        /// <returns></returns>
        public static bool StartProcessAndBypassUac(string applicationName, out PROCESS_INFORMATION procInfo, string workingDir)
        {
            uint   winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero;

            procInfo = new PROCESS_INFORMATION();

            if (string.IsNullOrWhiteSpace(workingDir) || !Directory.Exists(workingDir))
            {
                workingDir = null;
            }

            // obtain the currently active session id; every logged on user in the system has a unique session id

            var dwSessionId = (int)WTSGetActiveConsoleSessionId();

            // obtain the process id of the winlogon process that is running within the currently active session
            var processes = Process.GetProcessesByName(WardenProcess.WardenReferProcUac);

            if (processes.Length == 0 && !WardenProcess.WardenReferProcUac.Equals(WardenProcess.DefaultWardenReferProcUac))
            {
                //the overwritten process was gone, so lets use winlogon to prevent a crash.
                processes = Process.GetProcessesByName(WardenProcess.DefaultWardenReferProcUac);
            }
            foreach (var p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }
            if (winlogonPid == 0)
            {
                return(false);
            }
            // obtain a handle to the winlogon process
            var hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

            // obtain a handle to the access token of the winlogon process
            if (!OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, ref hPToken))
            {
                CloseHandle(hProcess);
                return(false);
            }

            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
            // I would prefer to not have to use a security attribute variable and to just
            // simply pass null and inherit (by default) the security attributes
            // of the existing token. However, in C# structures are value types and therefore
            // cannot be assigned the null value.
            var sa = new SECURITY_ATTRIBUTES();

            sa.Length = Marshal.SizeOf(sa);

            // copy the access token of the winlogon process; the newly created token will be a primary token
            if (
                !DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
                                  (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary,
                                  ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return(false);
            }

            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user
            // interaction with the new process.
            var si = new STARTUPINFO();

            si.cb        = Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default";
            // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

            // Mutate environment varaibles
            var env = IntPtr.Zero;

            if (!CreateEnvironmentBlock(ref env, hUserTokenDup, false))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return(false);
            }

            // flags that specify the priority and creation method of the process
            const int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT;

            // create a new process in the current user's logon session
            var result = CreateProcessAsUser(hUserTokenDup,   // client's access token
                                             null,            // file to execute
                                             applicationName, // command line
                                             ref sa,          // pointer to process SECURITY_ATTRIBUTES
                                             ref sa,          // pointer to thread SECURITY_ATTRIBUTES
                                             false,           // handles are not inheritable
                                             dwCreationFlags, // creation flags
                                             env,             // pointer to new environment block
                                             workingDir,      // name of current directory
                                             ref si,          // pointer to STARTUPINFO structure
                                             out procInfo     // receives information about new process
                                             );

            // invalidate the handles
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);

            return(result); // return the result
        }
Esempio n. 35
0
        public static void CreateProcessAsUser(string username, string domain, string password, string commandLine)
        {
            IntPtr hToken      = IntPtr.Zero;
            IntPtr hDupedToken = IntPtr.Zero;

            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();

            try
            {
                bool result = LogonUser(username, domain, password, (int)LOGON32_LOGON_INTERACTIVE, (int)LOGON32_PROVIDER_DEFAULT, ref hToken);

                if (!result)
                {
                    throw new ApplicationException("LogonUser failed");
                }

                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.Length = Marshal.SizeOf(sa);

                result = DuplicateTokenEx(
                    hToken,
                    GENERIC_ALL_ACCESS,
                    ref sa,
                    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                    (int)TOKEN_TYPE.TokenPrimary,
                    ref hDupedToken
                    );

                if (!result)
                {
                    throw new ApplicationException("DuplicateTokenEx failed");
                }


                STARTUPINFO si = new STARTUPINFO();
                si.cb        = Marshal.SizeOf(si);
                si.lpDesktop = "winsta0\\default";

                ProfileInfo info = new ProfileInfo();
                info.dwSize     = Marshal.SizeOf(info);
                info.lpUserName = username;
                info.dwFlags    = 1;

                result = LoadUserProfile(hDupedToken, ref info);

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();

                    throw new System.ComponentModel.Win32Exception(error);
                }

                IntPtr lpEnvironment;

                result = CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false);

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();

                    throw new System.ComponentModel.Win32Exception(error);
                }

                result = CreateProcessAsUser(
                    hDupedToken,
                    null,
                    commandLine,
                    ref sa, ref sa,
                    false, 0x00000400, lpEnvironment,
                    null, ref si, ref pi
                    );

                if (!result)
                {
                    int error = Marshal.GetLastWin32Error();

                    throw new System.ComponentModel.Win32Exception(error);
                }
            }
            finally
            {
                if (pi.hProcess != IntPtr.Zero)
                {
                    CloseHandle(pi.hProcess);
                }
                if (pi.hThread != IntPtr.Zero)
                {
                    CloseHandle(pi.hThread);
                }
                if (hDupedToken != IntPtr.Zero)
                {
                    CloseHandle(hDupedToken);
                }
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt
        /// </summary>
        /// <param name="applicationName">The name of the application to launch</param>
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>
        /// <returns></returns>
        public static bool StartProcessAndBypassUAC(String applicationName, out PROCESS_INFORMATION procInfo)
        {
            uint   winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;

            procInfo = new PROCESS_INFORMATION();

            // obtain the currently active session id; every logged on user in the system has a unique session id
            uint dwSessionId = WTSGetActiveConsoleSessionId();

            // obtain the process id of the winlogon process that is running within the currently active session
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }

            // obtain a handle to the winlogon process
            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

            // obtain a handle to the access token of the winlogon process
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                CloseHandle(hProcess);
                return(false);
            }

            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
            // I would prefer to not have to use a security attribute variable and to just
            // simply pass null and inherit (by default) the security attributes
            // of the existing token. However, in C# structures are value types and therefore
            // cannot be assigned the null value.
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();

            sa.Length = Marshal.SizeOf(sa);

            // copy the access token of the winlogon process; the newly created token will be a primary token
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return(false);
            }

            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user
            // interaction with the new process.
            STARTUPINFO si = new STARTUPINFO();

            si.cb        = (int)Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

            // flags that specify the priority and creation method of the process
            int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;

            // create a new process in the current user's logon session
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token
                                              null,                 // file to execute
                                              applicationName,      // command line
                                              ref sa,               // pointer to process SECURITY_ATTRIBUTES
                                              ref sa,               // pointer to thread SECURITY_ATTRIBUTES
                                              false,                // handles are not inheritable
                                              dwCreationFlags,      // creation flags
                                              IntPtr.Zero,          // pointer to new environment block
                                              null,                 // name of current directory
                                              ref si,               // pointer to STARTUPINFO structure
                                              out procInfo          // receives information about new process
                                              );

            // invalidate the handles
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);

            return(result); // return the result
        }
Esempio n. 37
0
 CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine,
                     ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes,
                     bool bInheritHandle, Int32 dwCreationFlags, IntPtr lpEnvrionment,
                     string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo,
                     ref PROCESS_INFORMATION lpProcessInformation);
Esempio n. 38
0
 static public extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, UInt32 dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In()] ref STARTUPINFO lpStartupInfo, [In, Out()] ref PROCESS_INFORMATION lpProcessInformation);
Esempio n. 39
0
        //public ICorDebugProcess CreateProcess(string lpApplicationName, string lpCommandLine, ref Debugger.Interop.CorDebug._SECURITY_ATTRIBUTES lpProcessAttributes, ref Debugger.Interop.CorDebug._SECURITY_ATTRIBUTES lpThreadAttributes, int bInheritHandles, uint dwCreationFlags, System.IntPtr lpEnvironment, string lpCurrentDirectory, uint lpStartupInfo, uint lpProcessInformation, CorDebugCreateProcessFlags debuggingFlags)
        public ICorDebugProcess CreateProcess(string lpApplicationName, string lpCommandLine, ref Debugger.Interop.CorDebug._SECURITY_ATTRIBUTES lpProcessAttributes, ref Debugger.Interop.CorDebug._SECURITY_ATTRIBUTES lpThreadAttributes, int bInheritHandles, uint dwCreationFlags, System.IntPtr lpEnvironment, string lpCurrentDirectory, STARTUPINFO lpStartupInfo, uint lpProcessInformation, CorDebugCreateProcessFlags debuggingFlags)
        {
            ICorDebugProcess ppProcess;

            Debugger.Interop.CorDebug.ICorDebugProcess out_ppProcess;
            this.WrappedObject.CreateProcess(lpApplicationName, lpCommandLine, ref lpProcessAttributes, ref lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, ((Debugger.Interop.CorDebug.CorDebugCreateProcessFlags)(debuggingFlags)), out out_ppProcess);
            ppProcess = ICorDebugProcess.Wrap(out_ppProcess);
            return(ppProcess);
        }
Esempio n. 40
0
        void CreateProcess()
        {
            bool spawnNew = !string.IsNullOrEmpty(_options.DumpFolderForNewlyStartedProcess);

            _processName = null;

            int pid;

            if (int.TryParse(_options.ProcessInfo, out pid))
            {
                _pid = pid;
            }
            else
            {
                // not numeric - let's try to find it by name
                var procs = Process.GetProcesses();
                foreach (var proc in procs)
                {
                    try
                    {
                        if (_options.ProcessInfo.Equals(proc.MainModule.ModuleName, StringComparison.OrdinalIgnoreCase))
                        {
                            _pid = proc.Id;
                            break;
                        }
                    }
                    catch
                    {
                        // just ignore it
                    }
                }
            }
            if (_pid > 0)
            {
                // process found - let's attach to it
                if (!DebuggingNativeMethods.DebugActiveProcess(_pid))
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                _processName = GetProcessName(_pid);
                return;
            }
            if (spawnNew)
            {
                // final try - let's try creating it (but only if -x option is set)
                var commandLine = _options.ProcessInfo + " " + string.Join(" ", _options.Args ?? new string[0]);

                var startupInfo          = new STARTUPINFO();
                var processInformation   = new PROCESS_INFORMATION();
                var processCreationFlags = ProcessCreationFlags.DEBUG_ONLY_THIS_PROCESS;
                if (_options.StartProcessInNewConsoleWindow)
                {
                    processCreationFlags |= ProcessCreationFlags.CREATE_NEW_CONSOLE;
                }
                bool res = ProcessNativeMethods.CreateProcess(null, new StringBuilder(commandLine),
                                                              null, null, false, processCreationFlags, IntPtr.Zero, null,
                                                              startupInfo, processInformation);
                if (!res)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                if (!DebuggingNativeMethods.DebugSetProcessKillOnExit(false))
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                _pid         = processInformation.dwProcessId;
                _processName = GetProcessName(_pid);
                return;
            }
            throw new ArgumentException("Something is wrong with the arguments - couldn't find or create a requested process.");
        }
Esempio n. 41
0
        internal static PROCESS_INFORMATION StartProcessAsCurrentUser(string appPath, Dictionary <string, string> envs,
                                                                      string args = "", string workDir = null, bool visible = true, string logsPath = null)
        {
            var hUserToken = IntPtr.Zero;
            var startInfo  = new STARTUPINFO();
            var procInfo   = new PROCESS_INFORMATION();
            var pEnv       = IntPtr.Zero;
            int iResultOfCreateProcessAsUser;

            appPath = WhereSearch(appPath);

            string cmdLine = "\"" + appPath + "\" " + args;

            startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));
            IntPtr hLogs = IntPtr.Zero;

            try
            {
                if (!GetSessionUserToken(ref hUserToken))
                {
                    throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed.");
                }

                uint dwCreationFlags = Kernel32.CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? Kernel32.CREATE_NEW_CONSOLE : Kernel32.CREATE_NO_WINDOW);
                dwCreationFlags |= Kernel32.CREATE_BREAKAWAY_FROM_JOB;

                startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
                startInfo.lpDesktop   = "winsta0\\default";
                startInfo.dwFlags     = Kernel32.STARTF_USESTDHANDLES;

                if (!String.IsNullOrEmpty(logsPath))
                {
                    SECURITY_ATTRIBUTES lpSecurityAttributes = new SECURITY_ATTRIBUTES();
                    lpSecurityAttributes.bInheritHandle = 1;
                    lpSecurityAttributes.nLength        = Marshal.SizeOf(lpSecurityAttributes);
                    hLogs = Kernel32.CreateFile(logsPath, Kernel32.DesiredAccess.FILE_APPEND_DATA, 0x00000003 //share read& w
                                                , lpSecurityAttributes, Kernel32.CreationDisposition.OPEN_ALWAYS, 0, IntPtr.Zero);

                    startInfo.hStdOutput = hLogs;
                    startInfo.hStdError  = hLogs;
                }


                if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
                {
                    throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
                }

                List <byte> envSB = ExtractMultiString(pEnv);
                if (envs != null)
                {
                    foreach (KeyValuePair <string, string> env in envs)
                    {
                        envSB.AddRange(Encoding.Unicode.GetBytes(env.Key + "=" + env.Value));
                        envSB.Add((byte)0);
                        envSB.Add((byte)0);
                    }
                }
                envSB.Add((byte)0);
                envSB.Add((byte)0);

                byte[] foo = envSB.ToArray();

                IntPtr envdst = Marshal.AllocHGlobal(foo.Length);
                Marshal.Copy(envSB.ToArray(), 0, envdst, envSB.ToArray().Length);


                if (!CreateProcessAsUser(hUserToken,
                                         null,    // Application Name
                                         cmdLine, // Command Line
                                         IntPtr.Zero,
                                         IntPtr.Zero,
                                         true,
                                         dwCreationFlags,
                                         envdst,
                                         workDir, // Working directory
                                         ref startInfo,
                                         out procInfo))
                {
                    iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
                    throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.  Error Code -" + iResultOfCreateProcessAsUser);
                }


                iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
            }
            finally
            {
                CloseHandle(hUserToken);


                if (pEnv != IntPtr.Zero)
                {
                    DestroyEnvironmentBlock(pEnv);
                }
            }

            return(procInfo);
        }
Esempio n. 42
0
 private static extern int CreateProcessA(string lpApplicationName, string lpCommandLine, int lpProcessAttributes, int lpThreadAttributes, int bInheritHandles, int dwCreationFlags, int lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation);
Esempio n. 43
0
        public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true)
        {
            var hUserToken = IntPtr.Zero;
            var startInfo  = new STARTUPINFO();
            var procInfo   = new PROCESS_INFORMATION();
            var pEnv       = IntPtr.Zero;
            int iResultOfCreateProcessAsUser;

            startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));

            try
            {
                if (!GetSessionUserToken(ref hUserToken))
                {
                    throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed.");
                }

                uint dwCreationFlags;
                if (visible)
                {
                    dwCreationFlags       = CREATE_UNICODE_ENVIRONMENT | (uint)(CREATE_NO_WINDOW);
                    startInfo.wShowWindow = (short)(SW.SW_HIDE);
                }
                else
                {
                    dwCreationFlags       = CREATE_UNICODE_ENVIRONMENT | (uint)(CREATE_NO_WINDOW);
                    startInfo.wShowWindow = (short)(SW.SW_HIDE);
                }

                startInfo.lpDesktop = "winsta0\\default";

                if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
                {
                    throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
                }

                if (!CreateProcessAsUser(hUserToken,
                                         appPath, // Application Name
                                         cmdLine, // Command Line
                                         IntPtr.Zero,
                                         IntPtr.Zero,
                                         false,
                                         dwCreationFlags,
                                         pEnv,
                                         workDir, // Working directory
                                         ref startInfo,
                                         out procInfo))
                {
                    iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
                    throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.  Error Code -" + iResultOfCreateProcessAsUser);
                }

                iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
            }
            finally
            {
                CloseHandle(hUserToken);
                if (pEnv != IntPtr.Zero)
                {
                    DestroyEnvironmentBlock(pEnv);
                }
                CloseHandle(procInfo.hThread);
                CloseHandle(procInfo.hProcess);
            }

            return(true);
        }
Esempio n. 44
0
        public static Win32Process StartProcessAsUser(WindowsIdentity winIdentity, string applicationName, string commandLine, string workingDirectory, Win32NativeEnvironmentBlock environment, out Stream stdin, out Stream stdout, out Stream stderror)
        {
            STARTUPINFO si = new STARTUPINFO();

            si.cb = Marshal.SizeOf(typeof(STARTUPINFO));

            /*
             * When a process is started using CreateProcessAsUser function, the process will be started into a windowstation
             * and desktop combination based on the value of lpDesktop in the STARTUPINFO structure parameter:
             * lpDesktop = "<windowsta>\<desktop>"; the system will try to start the process into that windowstation and desktop.
             * lpDesktop = NULL; the system will try to use the same windowstation and desktop as the calling process if the system is associated with the interactive windowstation.
             * lpDesktop = <somevalue>; the system will create a new windowstation and desktop that you cannot see.
             * lpDesktop = ""; it will either create a new windowstation and desktop that you cannot see, or if one has been created by means of a prior call by using the same access token, the existing windowstation and desktop will be used.
             */
            si.lpDesktop = "";

            IntPtr stdinRead, stdinWrite, stdoutRead, stdoutWrite, stderrorRead, stderrorWrite;

            SECURITY_ATTRIBUTES sa = default(SECURITY_ATTRIBUTES);

            sa.nLength = Marshal.SizeOf(sa);
            sa.lpSecurityDescriptor = IntPtr.Zero;
            sa.bInheritHandle       = true;

            if (!CreatePipe(out stdinRead, out stdinWrite, ref sa, 0))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!SetHandleInformation(stdinWrite, HANDLE_FLAGS.INHERIT, HANDLE_FLAGS.None))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!CreatePipe(out stdoutRead, out stdoutWrite, ref sa, 0))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!SetHandleInformation(stdoutRead, HANDLE_FLAGS.INHERIT, HANDLE_FLAGS.None))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!CreatePipe(out stderrorRead, out stderrorWrite, ref sa, 0))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!SetHandleInformation(stderrorRead, HANDLE_FLAGS.INHERIT, HANDLE_FLAGS.None))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            si.dwFlags    = STARTF_USESTDHANDLES;
            si.hStdInput  = stdinRead;
            si.hStdOutput = stdoutWrite;
            si.hStdError  = stderrorWrite;

            SECURITY_ATTRIBUTES processAttr = CreateSecurityAttributes(winIdentity == null ? WellKnownSidType.AuthenticatedUserSid : WellKnownSidType.NetworkServiceSid);
            SECURITY_ATTRIBUTES threadAttr  = CreateSecurityAttributes(winIdentity == null ? WellKnownSidType.AuthenticatedUserSid : WellKnownSidType.NetworkServiceSid);

            lock (_createProcessLock) {
                PROCESS_INFORMATION pi;
                ErrorModes          oldErrorMode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);
                try {
                    if (winIdentity == null)
                    {
                        if (!CreateProcess(applicationName, commandLine, ref processAttr, ref threadAttr, true,
                                           (uint)(CREATE_PROCESS_FLAGS.CREATE_UNICODE_ENVIRONMENT | CREATE_PROCESS_FLAGS.CREATE_NO_WINDOW),
                                           environment.NativeEnvironmentBlock,
                                           workingDirectory,
                                           ref si,
                                           out pi))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        if (!CreateProcessAsUser(
                                winIdentity.Token, applicationName, commandLine, ref processAttr, ref threadAttr, true,
                                (uint)(CREATE_PROCESS_FLAGS.CREATE_UNICODE_ENVIRONMENT | CREATE_PROCESS_FLAGS.CREATE_NO_WINDOW),
                                environment.NativeEnvironmentBlock,
                                workingDirectory,
                                ref si,
                                out pi))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }

                    stdin    = new FileStream(new SafeFileHandle(stdinWrite, true), FileAccess.Write, 0x1000, false);
                    stdout   = new FileStream(new SafeFileHandle(stdoutRead, true), FileAccess.Read, 0x1000, false);
                    stderror = new FileStream(new SafeFileHandle(stderrorRead, true), FileAccess.Read, 0x1000, false);
                } finally {
                    SetErrorMode(oldErrorMode);

                    if (processAttr.lpSecurityDescriptor != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(processAttr.lpSecurityDescriptor);
                    }

                    if (threadAttr.lpSecurityDescriptor != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(threadAttr.lpSecurityDescriptor);
                    }
                }

                return(new Win32Process(pi));
            }
        }
Esempio n. 45
0
        // 创建管道,将输出通过管道转送到日志文件,然后读取日志文件内容打印到控制台
        private void CreatePipProcess(string kernelExeFileFullName, string arguments)
        {
            SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES {
                bInheritHandle       = true,
                lpSecurityDescriptor = IntPtr.Zero,
                length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES))
            };

            //set the bInheritHandle flag so pipe handles are inherited

            saAttr.lpSecurityDescriptor = IntPtr.Zero;
            //get handle to current stdOut

            IntPtr mypointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STARTUPINFO)));

            Marshal.StructureToPtr(saAttr, mypointer, true);
            var bret = CreatePipe(out _hReadOut, out _hWriteOut, mypointer, 0);

            if (!bret)
            {
                int lasterr = Marshal.GetLastWin32Error();
                VirtualRoot.RaiseEvent(new StartingMineFailedEvent($"管道型进程创建失败 lasterr:{lasterr.ToString()}"));
                return;
            }

            const uint STARTF_USESHOWWINDOW  = 0x00000001;
            const uint STARTF_USESTDHANDLES  = 0x00000100;
            const uint NORMAL_PRIORITY_CLASS = 0x00000020;
            //const short SW_SHOW = 5;
            const short SW_HIDE             = 0;
            const int   HANDLE_FLAG_INHERIT = 1;

            //ensure the read handle to pipe for stdout is not inherited
            SetHandleInformation(_hReadOut, HANDLE_FLAG_INHERIT, 0);
            ////Create pipe for the child process's STDIN
            STARTUPINFO lpStartupInfo = new STARTUPINFO {
                cb          = (uint)Marshal.SizeOf(typeof(STARTUPINFO)),
                dwFlags     = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW,
                wShowWindow = SW_HIDE, // SW_HIDE; //SW_SHOW
                hStdOutput  = _hWriteOut,
                hStdError   = _hWriteOut,
                hStdInput   = IntPtr.Zero
            };
            StringBuilder lpEnvironment = new StringBuilder();
            // 复制父进程的环境变量
            var dic = Environment.GetEnvironmentVariables();

            // 追加环境变量
            foreach (var item in this.CoinKernel.EnvironmentVariables)
            {
                dic.Add(item.Key, item.Value);
            }
            foreach (var key in dic.Keys)
            {
                if (key == null || key.ToString().Contains("\0"))
                {
                    continue;
                }
                var value = dic[key];
                if (value == null || value.ToString().Contains("\0"))
                {
                    continue;
                }
                lpEnvironment.Append($"{key.ToString()}={value.ToString()}\0");
            }
            if (CreateProcess(
                    lpApplicationName: null,
                    lpCommandLine: new StringBuilder($"\"{kernelExeFileFullName}\" {arguments}"),
                    lpProcessAttributes: IntPtr.Zero,
                    lpThreadAttributes: IntPtr.Zero,
                    bInheritHandles: true,
                    dwCreationFlags: NORMAL_PRIORITY_CLASS,
                    lpEnvironment: lpEnvironment,
                    lpCurrentDirectory: Path.GetDirectoryName(kernelExeFileFullName),// 内核exe所在的目录
                    lpStartupInfo: ref lpStartupInfo,
                    lpProcessInformation: out PROCESS_INFORMATION processInfo))
            {
                try {
                    this.KernelProcess = Process.GetProcessById((int)processInfo.dwProcessId);
                }
                catch {
                    this.Close();
                    VirtualRoot.RaiseEvent(new StartingMineFailedEvent($"内核已退出"));
                    return;
                }

                Task.Factory.StartNew(() => {
                    using (FileStream fs = new FileStream(this.LogFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
                        const byte r  = (byte)'\r';
                        byte[] buffer = new byte[NTKeyword.IntK];
                        int ret;
                        // Read会阻塞,直到读取到字符或者hWriteOut被关闭
                        while ((ret = Read(buffer, 0, buffer.Length, _hReadOut)) > 0)
                        {
                            byte[] data = new byte[ret];
                            int n       = 0;
                            for (int i = 0; i < ret; i++)
                            {
                                if (buffer[i] != r)
                                {
                                    data[n] = buffer[i];
                                    n++;
                                }
                            }
                            fs.Write(data, 0, n);
                            fs.Flush();
                        }
                    }
                    CloseHandle(_hReadOut);
                }, TaskCreationOptions.LongRunning);
                ReadPrintLoopLogFileAsync(isWriteToConsole: true);
            }
Esempio n. 46
0
 public static extern bool CreateProcess(
     [MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName, StringBuilder lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes,
     SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment,
     [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION lpProcessInformation);
Esempio n. 47
0
        public static Process RunAsDesktopUser(ProcessStartInfo startInfo)
        {
            if (string.IsNullOrWhiteSpace(startInfo.FileName))
            {
                throw new ArgumentException("Value FileName cannot be null or whitespace.", nameof(startInfo));
            }

            // To start process as shell user you will need to carry out these steps:
            // 1. Enable the SeIncreaseQuotaPrivilege in your current token
            // 2. Get an HWND representing the desktop shell (GetShellWindow)
            // 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
            // 4. Open that process(OpenProcess)
            // 5. Get the access token from that process (OpenProcessToken)
            // 6. Make a primary token with that token(DuplicateTokenEx)
            // 7. Start the new process with that primary token(CreateProcessWithTokenW)

            var hProcessToken = IntPtr.Zero;

            // Enable SeIncreaseQuotaPrivilege in this process.  (This won't work if current process is not elevated.)
            try {
                var process = GetCurrentProcess();
                if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
                {
                    return(null);
                }

                var tkp = new TOKEN_PRIVILEGES {
                    PrivilegeCount = 1,
                    Privileges     = new LUID_AND_ATTRIBUTES[1]
                };

                if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
                {
                    return(null);
                }

                tkp.Privileges[0].Attributes = 0x00000002;

                if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    return(null);
                }
            } finally {
                CloseHandle(hProcessToken);
            }

            // Get an HWND representing the desktop shell.
            // CAVEATS:  This will fail if the shell is not running (crashed or terminated), or the default shell has been
            // replaced with a custom shell.  This also won't return what you probably want if Explorer has been terminated and
            // restarted elevated.
            var hwnd = GetShellWindow();

            if (hwnd == IntPtr.Zero)
            {
                return(null);
            }

            var hShellProcess      = IntPtr.Zero;
            var hShellProcessToken = IntPtr.Zero;
            var hPrimaryToken      = IntPtr.Zero;

            try {
                // Get the PID of the desktop shell process.
                uint dwPID;
                if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
                {
                    return(null);
                }

                // Open the desktop shell process in order to query it (get the token)
                hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
                if (hShellProcess == IntPtr.Zero)
                {
                    return(null);
                }

                // Get the process token of the desktop shell.
                if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
                {
                    return(null);
                }

                var dwTokenRights = 395U;

                // Duplicate the shell's process token to get a primary token.
                // Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
                if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
                {
                    return(null);
                }

                // Start the target process with the new token.
                var si = new STARTUPINFO();
                var pi = new PROCESS_INFORMATION();
                if (!CreateProcessWithTokenW(hPrimaryToken, 0, startInfo.FileName, startInfo.Arguments, 0, IntPtr.Zero, startInfo.WorkingDirectory, ref si, out pi))
                {
                    return(null);
                }

                return(Process.GetProcessById(pi.dwProcessId));
            } finally {
                CloseHandle(hShellProcessToken);
                CloseHandle(hPrimaryToken);
                CloseHandle(hShellProcess);
            }
        }
Esempio n. 48
0
        public static unsafe bool Execute(LoadParams args)
        {
            bool isWow64 = false;
            PROCESS_INFORMATION lpProcesSystemNetCertPolicyValidationCallbackv = new PROCESS_INFORMATION();
            CONTEXT             context = new CONTEXT()
            {
                ContextFlags = 1048603
            };
            IntPtr            lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU;
            IMAGE_DOS_HEADER *imageDosHeaderPtr;
            IMAGE_NT_HEADERS *imageNtHeadersPtr;

            fixed(byte *numPtr = args.Body)
            {
                lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU = (IntPtr)((void *)numPtr);
                imageDosHeaderPtr = (IMAGE_DOS_HEADER *)numPtr;
                imageNtHeadersPtr = (IMAGE_NT_HEADERS *)(numPtr + imageDosHeaderPtr->e_lfanew);
            }

            if (imageDosHeaderPtr->e_magic != (ushort)23117 || imageNtHeadersPtr->Signature != 17744U || imageNtHeadersPtr->OptionalHeader.Magic != (ushort)267)
            {
                return(false);
            }
            Buffer.SetByte((Array)args.Body, 920, (byte)2);
            STARTUPINFO lpStartupInfo = new STARTUPINFO();

            lpStartupInfo.cb          = Marshal.SizeOf((object)lpStartupInfo);
            lpStartupInfo.wShowWindow = (short)0;
            using (LibInvoker libInvoker1 = new LibInvoker("kernel32.dll"))
            {
                using (LibInvoker libInvoker2 = new LibInvoker("ntdll.dll"))
                {
                    if (!libInvoker1.CastToDelegate <NativeDelegates.CreateProcessInternalWDelegate>("CreateProcessInternalW")(0U, (string)null, args.AppPath, IntPtr.Zero, IntPtr.Zero, false, 134217740U, IntPtr.Zero, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), ref lpStartupInfo, out lpProcesSystemNetCertPolicyValidationCallbackv, 0U))
                    {
                        if (lpProcesSystemNetCertPolicyValidationCallbackv.hProcess != IntPtr.Zero && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                        {
                            int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                            int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                        }
                        return(false);
                    }
                    int    num3      = libInvoker1.CastToDelegate <NativeDelegates.IsWow64ProcessDelegate>("IsWow64Process")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, ref isWow64) ? 1 : 0;
                    IntPtr imageBase = (IntPtr)((long)imageNtHeadersPtr->OptionalHeader.ImageBase);
                    int    num4      = (int)libInvoker2.CastToDelegate <NativeDelegates.NtUnmapViewOfSectionDelegate>("NtUnmapViewOfSection")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase);
                    if (libInvoker1.CastToDelegate <NativeDelegates.VirtualAllocExDelegate>("VirtualAllocEx")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase, imageNtHeadersPtr->OptionalHeader.SizeOfImage, 12288U, 64U) == IntPtr.Zero && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                    {
                        int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                        int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                        return(false);
                    }
                    if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase, lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU, imageNtHeadersPtr->OptionalHeader.SizeOfHeaders, IntPtr.Zero) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                    {
                        int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                        int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                        return(false);
                    }
                    for (ushort index = 0; (int)index < (int)imageNtHeadersPtr->FileHeader.NumberOfSections; ++index)
                    {
                        IMAGE_SECTION_HEADER *imageSectionHeaderPtr = (IMAGE_SECTION_HEADER *)((ulong)lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + (ulong)imageDosHeaderPtr->e_lfanew + (ulong)Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)) + (ulong)(Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (int)index));
                        if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)(imageBase.ToInt64() + (long)imageSectionHeaderPtr->VirtualAddress), (IntPtr)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + (long)imageSectionHeaderPtr->PointerToRawData), imageSectionHeaderPtr->SizeOfRawData, IntPtr.Zero) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                        {
                            int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                            int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                            return(false);
                        }
                    }
                    if (isWow64)
                    {
                        if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("Wow64GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                        {
                            int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                            int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                            return(false);
                        }
                    }
                    else if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                    {
                        int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                        int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                        return(false);
                    }
                    IntPtr num5   = Marshal.AllocHGlobal(8);
                    ulong  int64  = (ulong)imageBase.ToInt64();
                    byte[] source = new byte[8];
                    for (int index = 0; index < 8; ++index)
                    {
                        source[index] = (byte)(int64 >> index * 8);
                        if (index == 7)
                        {
                            Marshal.Copy(source, 0, num5, 8);
                        }
                    }
                    if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)((long)context.Ebx + 8L), num5, 4U, IntPtr.Zero))
                    {
                        Marshal.FreeHGlobal(num5);
                        if (libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                        {
                            int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                            int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                            return(false);
                        }
                    }
                    Marshal.FreeHGlobal(num5);
                    context.Eax = (uint)((ulong)imageBase.ToInt64() + (ulong)imageNtHeadersPtr->OptionalHeader.AddressOfEntryPoint);
                    if (isWow64)
                    {
                        if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("Wow64SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                        {
                            int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                            int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                            return(false);
                        }
                    }
                    else if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1))
                    {
                        int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                        int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                        return(false);
                    }
                    int num6 = (int)libInvoker1.CastToDelegate <NativeDelegates.ResumeThreadDelegate>("ResumeThread")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread);
                    int num7 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0;
                    int num8 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0;
                }
            }
            return(true);
        }
Esempio n. 49
0
		public static void Start(string filename, string arguments) {
			bool processCreated = false;

			if (Environment.OSVersion.Version.Major >= 6 && IsUserAnAdmin()) {
				//Get window handle representing the desktop shell.  This might not work if there is no shell window, or when
				//using a custom shell.  Also note that we're assuming that the shell is not running elevated.
				IntPtr hShellWnd = GetShellWindow();
				if (hShellWnd == IntPtr.Zero) {
					MessageBox.Show("Unable to locate shell window; you might be using a custom shell");
					return;
				}

				//Get the ID of the desktop shell process.
				int dwShellPID;
				GetWindowThreadProcessId(hShellWnd, out dwShellPID);
				if (dwShellPID != 0) {
					//Open the desktop shell process in order to get the process token.
					// PROCESS_QUERY_INFORMATION = 0x00000400
					IntPtr hShellProcess = OpenProcess(0x0400, false, dwShellPID);

					if (hShellProcess != IntPtr.Zero) {
						IntPtr hShellProcessToken;

						//Get the process token of the desktop shell.

						//TOKEN_DUPLICATE = 0x0002
						if (OpenProcessToken(hShellProcess, 0x2, out hShellProcessToken)) {
							IntPtr hPrimaryToken;
							//Duplicate the shell's process token to get a primary token.

							//TOKEN_QUERY = 0x0008
							//TOKEN_ASSIGN_PRIMARY = 0x0001
							//TOKEN_DUPLICATE = 0x0002
							//TOKEN_ADJUST_DEFAULT = 0x0080
							//TOKEN_ADJUST_SESSIONID = 0x0100;
							const uint dwTokenRights = 0x0008 | 0x0001 | 0x0002 | 0x0080 | 0x0100;
							//SecurityImpersonation = 2
							//TokenPrimary = 1
							if (DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, 2, 1, out hPrimaryToken)) {
								//Start the target process with the new token.
								PROCESS_INFORMATION pi;

								var si = new STARTUPINFO();
								si.cb = Marshal.SizeOf(si);

								// build the arguments string
								if (string.IsNullOrEmpty(arguments))
									arguments = filename;
								else
									arguments = filename + " " + arguments;

								processCreated = CreateProcessWithTokenW(hPrimaryToken, 0, filename, arguments, 0, IntPtr.Zero, null, ref si,
								                                         out pi);

								if (processCreated) {
									//return Process.GetProcessById(pi.dwProcessId);
									CloseHandle(pi.hProcess);
									CloseHandle(pi.hThread);
								}

								if (hPrimaryToken != IntPtr.Zero)
									CloseHandle(hPrimaryToken);
							}

							if (hShellProcessToken != IntPtr.Zero)
								CloseHandle(hShellProcessToken);
						}

						if (hShellProcess != IntPtr.Zero)
							CloseHandle(hShellProcess);
					}
				}
			}

			// the process failed to be created for any number of reasons
			// just create it using the regular method
			if (!processCreated) {
				Process.Start(filename, arguments);
			}
		}
Esempio n. 50
0
        public static int CreateProcessAsAdmin(int sessionId, string filename, string arugments)
        {
            IntPtr hToken = IntPtr.Zero;

            try
            {
                Process process = Array.Find(Process.GetProcessesByName("winlogon"), p => p.SessionId == sessionId);
                if (process != null)
                {
                    IntPtr hProcess = OpenProcess(MAXIMUM_ALLOWED, false, (uint)process.Id);
                    process.Close();
                    if (hProcess != IntPtr.Zero)
                    {
                        //Debug.Assert(hProcess == process.Handle);
                        if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hToken))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error())
                                  {
                                      Source = "OpenProcessToken"
                                  }
                        }
                        ;

                        CloseHandle(hProcess);
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error())
                              {
                                  Source = "OpenProcess"
                              }
                    };
                }
                else
                {
                    TraceLog.WriteLineWarning("Process winlogon not find at sessionId: " + sessionId);
                }
            }
            catch (Exception ex) { TraceLog.WriteException(ex); }

            int processId = 0;

            try
            {
                if (hToken != IntPtr.Zero)
                {
                    IntPtr hUserTokenDup   = IntPtr.Zero;
                    SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                    sa.Length = Marshal.SizeOf(sa);

                    if (DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
                    {
                        STARTUPINFO si = new STARTUPINFO();
                        si.cb        = (int)Marshal.SizeOf(si);
                        si.lpDesktop = @"winsta0\default";

                        PROCESS_INFORMATION pi;
                        string cmdLine = string.Format("{0} {1}", filename, arugments);
                        bool   ret     = CreateProcessAsUser(hUserTokenDup,                                     // client's access token
                                                             null,                                              // file to execute
                                                             cmdLine,                                           // command line
                                                             ref sa,                                            // pointer to process SECURITY_ATTRIBUTES
                                                             ref sa,                                            // pointer to thread SECURITY_ATTRIBUTES
                                                             false,                                             // handles are not inheritable
                                                             0,                                                 // creation flags
                                                             IntPtr.Zero,                                       // pointer to new environment block
                                                             null,                                              // name of current directory
                                                             ref si,                                            // pointer to STARTUPINFO structure
                                                             out pi                                             // receives information about new process
                                                             );
                        CloseHandle(hUserTokenDup);
                        if (ret)
                        {
                            processId = (int)pi.dwProcessId;
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error())
                                  {
                                      Source = "CreateProcessAsUser"
                                  }
                        };
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error())
                              {
                                  Source = "DuplicateTokenEx"
                              }
                    };

                    CloseHandle(hToken);
                }
            }
            catch (Exception ex) { TraceLog.WriteException(ex); }
            return(processId);
        }
Esempio n. 51
0
 public static extern uint CreateProcess([In] string pszImageName, [In][Out] string pszCmdLine, [In] IntPtr psaProcess, [In] IntPtr psaThread, [In] uint fInheritHandles, [In] PROCESS_CREATION_FLAG fdwCreate, [In] IntPtr pvEnvironment, [In] IntPtr pszCurDir, [In] ref STARTUPINFO psiStartInfo, out PROCESS_INFORMATION pProcInfo);
Esempio n. 52
0
        public static bool OpenInteractiveProcess(string applicationName,
                                                  int targetSessionId,
                                                  bool forceConsoleSession,
                                                  string desktopName,
                                                  bool hiddenWindow,
                                                  out PROCESS_INFORMATION procInfo)
        {
            uint   winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;

            procInfo = new PROCESS_INFORMATION();

            // If not force console, find target session.  If not present,
            // use last active session.
            var dwSessionId = Kernel32.WTSGetActiveConsoleSessionId();

            if (!forceConsoleSession)
            {
                var activeSessions = GetActiveSessions();
                if (activeSessions.Any(x => x.ID == targetSessionId))
                {
                    dwSessionId = (uint)targetSessionId;
                }
                else
                {
                    dwSessionId = activeSessions.Last().ID;
                }
            }

            // Obtain the process ID of the winlogon process that is running within the currently active session.
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }

            // Obtain a handle to the winlogon process.
            hProcess = Kernel32.OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

            // Obtain a handle to the access token of the winlogon process.
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                Kernel32.CloseHandle(hProcess);
                return(false);
            }

            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser.
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();

            sa.Length = Marshal.SizeOf(sa);

            // Copy the access token of the winlogon process; the newly created token will be a primary token.
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, out hUserTokenDup))
            {
                Kernel32.CloseHandle(hProcess);
                Kernel32.CloseHandle(hPToken);
                return(false);
            }

            // By default, CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user
            // interaction with the new process.
            STARTUPINFO si = new STARTUPINFO();

            si.cb        = Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\" + desktopName;

            // Flags that specify the priority and creation method of the process.
            uint dwCreationFlags;

            if (hiddenWindow)
            {
                dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW;
                si.dwFlags      = STARTF_USESHOWWINDOW;
                si.wShowWindow  = 0;
            }
            else
            {
                dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE;
            }

            // Create a new process in the current user's logon session.
            bool result = CreateProcessAsUser(hUserTokenDup, null, applicationName, ref sa, ref sa, false, dwCreationFlags, IntPtr.Zero, null, ref si, out procInfo);

            // Invalidate the handles.
            Kernel32.CloseHandle(hProcess);
            Kernel32.CloseHandle(hPToken);
            Kernel32.CloseHandle(hUserTokenDup);

            return(result);
        }