public static void Run(Settings settings, string bin, long ip, ushort port) { var binpath = Path.Combine(settings.ClientDirectory, bin); var startupInfo = new Startupinfo(); _processInfo = new ProcessInformation(); //TODO -- what to do if !success? var success = CreateProcess(binpath, string.Format("\"{0}\" {1} {2}", binpath.Trim(), ip, port), IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CreateSuspended | ProcessCreationFlags.CreateDefaultErrorMode, IntPtr.Zero, null, ref startupInfo, out _processInfo); DllInjector.GetInstance.BInject(_processInfo.DwProcessId, Path.Combine(settings.ClientDirectory, "Login.dll")); if (settings.DisableDark) { DllInjector.GetInstance.BInject(_processInfo.DwProcessId, Path.Combine(settings.ClientDirectory, "LinS3EP1.dll")); } var closeNpPath = Path.Combine(settings.ClientDirectory, "closenp.dll"); //just in case the user doesnt copy closenp to their directory if (File.Exists(closeNpPath)) { DllInjector.GetInstance.BInject(_processInfo.DwProcessId, closeNpPath); } System.Threading.Thread.Sleep(1000); var tHandle = _processInfo.HThread; ResumeThread(tHandle); }
private static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, ProcessCreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
private Startupinfo GetStartupInfo() { var si = new Startupinfo(); si.cb = Marshal.SizeOf(si); si.lpDesktop = @"winsta0\default"; return(si); }
public static bool launch(string game, string arguments) { String binPath; String exe; String dll; //Lets get our games straight if (game == "ETS2") { Environment.SetEnvironmentVariable("SteamGameId", "227300"); Environment.SetEnvironmentVariable("SteamAppID", "227300"); binPath = Launcher.ETS2Location + "\\bin\\win_x64"; exe = "\\eurotrucks2.exe"; dll = "\\core_ets2mp.dll"; arguments += " -64bit"; } else if (game == "ATS") { Environment.SetEnvironmentVariable("SteamGameId", "270880"); Environment.SetEnvironmentVariable("SteamAppID", "270880"); binPath = Launcher.ATSLocation + "\\bin\\win_x64"; exe = "\\amtrucks.exe"; dll = "\\core_atsmp.dll"; arguments += " -64bit"; } else { return(false); //Invalid game, lets not do this } //Intialize variables 'n stuff ProcessInformation processInformation = default(ProcessInformation); Startupinfo startupinfo = default(Startupinfo); SecurityAttributes securityAttributes = default(SecurityAttributes); SecurityAttributes securityAttributes2 = default(SecurityAttributes); startupinfo.cb = Marshal.SizeOf(startupinfo); securityAttributes.nLength = Marshal.SizeOf(securityAttributes); securityAttributes2.nLength = Marshal.SizeOf(securityAttributes2); //Lets run the game! if (!CreateProcess(binPath + exe, arguments, ref securityAttributes, ref securityAttributes2, false, 4u, IntPtr.Zero, binPath, ref startupinfo, out processInformation)) { return(false); } if (!Inject(processInformation.hProcess, Launcher.TruckersMPLocation + dll)) { return(false); } ResumeThread(processInformation.hThread); return(true); }
public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
public extern static int CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SecurityAttributes lpProcessAttributes, ref SecurityAttributes lpThreadAttributes, Int32 bInheritHandles, UInt32 dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
public static extern bool CreateProcessWithLogonW(string lpUsername, string lpDomain, string lpPassword, LogonFlags dwLogonFlags, string lpApplicationName, string lpCommandLine, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInfo);
public static void Start(string cmdArgs) { // 1. Get the shell var shell = NativeMethods.GetShellWindow(); if (shell == IntPtr.Zero) { throw new Exception("Could not find shell window"); } // 2. Copy the access token of the process NativeMethods.GetWindowThreadProcessId(shell, out uint shellProcessId); var hShellProcess = NativeMethods.OpenProcess(0x00000400 /* QueryInformation */, false, (int)shellProcessId); if (!NativeMethods.OpenProcessToken(hShellProcess, 2 /* TOKEN_DUPLICATE */, out IntPtr hShellToken)) { throw new Win32Exception(); } // 3. Dublicate the acess token uint tokenAccess = 8 /*TOKEN_QUERY*/ | 1 /*TOKEN_ASSIGN_PRIMARY*/ | 2 /*TOKEN_DUPLICATE*/ | 0x80 /*TOKEN_ADJUST_DEFAULT*/ | 0x100 /*TOKEN_ADJUST_SESSIONID*/; var securityAttributes = new SecurityAttributes(); NativeMethods.DuplicateTokenEx( hShellToken, tokenAccess, ref securityAttributes, 2 /* SecurityImpersonation */, 1 /* TokenPrimary */, out IntPtr hToken); // 4. Create a new process with the copied token var si = new Startupinfo(); si.cb = Marshal.SizeOf(si); if (!NativeMethods.CreateProcessWithTokenW( hToken, 0x00000002 /* LogonNetcredentialsOnly */, null, cmdArgs, 0x00000010 /* CreateNewConsole */, IntPtr.Zero, null, ref si, out ProcessInformation _)) { throw new Win32Exception(); } }
private static ProcessInformation? CreateProcess(string childProcName, IntPtr logonUserToken, string arguments) { ProcessInformation processInformation; var tStartUpInfo = new Startupinfo { cb = Marshal.SizeOf(typeof(Startupinfo)) }; bool childProcStarted = CreateProcessAsUser( logonUserToken, childProcName, Path.GetFileName(childProcName) + " " + arguments, IntPtr.Zero, IntPtr.Zero, false, // Does NOT inherit parent's handles. 0, // No any specific creation flag. null, // Default environment path. null, // Default current directory. ref tStartUpInfo, // Process Startup Info. out processInformation // Process information to be returned. ); return childProcStarted ? (ProcessInformation?) processInformation : null; }
public static IntPtr CreateNewProcessSuspend(string exePath, string cmdLine) { var application = exePath; var commandLine = cmdLine; ProcessInformation pInfo; var sInfo = new Startupinfo(); var pSec = new SecurityAttributes(); var tSec = new SecurityAttributes(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); //Open Notepad CreateProcess(application, commandLine, ref pSec, ref tSec, false, (uint)CreateProcessFlags.CreateSuspended, IntPtr.Zero, null, ref sInfo, out pInfo); return(pInfo.hProcess); }
private static ProcessInformation?CreateProcess(string childProcName, IntPtr logonUserToken, string arguments) { ProcessInformation processInformation; var tStartUpInfo = new Startupinfo { cb = Marshal.SizeOf(typeof(Startupinfo)) }; bool childProcStarted = CreateProcessAsUser( logonUserToken, childProcName, Path.GetFileName(childProcName) + " " + arguments, IntPtr.Zero, IntPtr.Zero, false, // Does NOT inherit parent's handles. 0, // No any specific creation flag. null, // Default environment path. null, // Default current directory. ref tStartUpInfo, // Process Startup Info. out processInformation // Process information to be returned. ); return(childProcStarted ? (ProcessInformation?)processInformation : null); }
public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
/// <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 ProcessInformation procInfo) { uint winlogonPid = 0; IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero; procInfo = new ProcessInformation(); // 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 IntPtr hProcess = OpenProcess(MaximumAllowed, false, winlogonPid); // obtain a handle to the access token of the winlogon process if (!OpenProcessToken(hProcess, TokenDuplicate, 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 SecurityAttributes(); 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, MaximumAllowed, ref sa, (int)SecurityImpersonationLevel.SecurityIdentification, (int)TokenType.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 // flags that specify the priority and creation method of the process const int dwCreationFlags = NormalPriorityClass | CreateNewConsole; // 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 }
public static extern bool CreateProcessWithTokenW( IntPtr hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
/// <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 ProcessInformation procInfo) { uint winlogonPid = 0; IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero; procInfo = new ProcessInformation(); // 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 IntPtr hProcess = OpenProcess(MaximumAllowed, false, winlogonPid); // obtain a handle to the access token of the winlogon process if (!OpenProcessToken(hProcess, TokenDuplicate, 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 SecurityAttributes(); 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, MaximumAllowed, ref sa, (int)SecurityImpersonationLevel.SecurityIdentification, (int)TokenType.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 // flags that specify the priority and creation method of the process const int dwCreationFlags = NormalPriorityClass | CreateNewConsole; // 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 }
/// <summary> /// Runs a process via impersonation /// </summary> /// <param name="filename"></param> /// <param name="commandLine"></param> /// <param name="workingDirectory"></param> /// <param name="sessionId">if equals -1 (default) will run in console/admin session</param> /// <param name="logger"></param> /// <returns></returns> public static RunAsResult RunAs(string filename, string commandLine, string workingDirectory, int sessionId = -1) { var hToken = new IntPtr(); var si = new Startupinfo(); si.lpReserved = null; int dwSessionId; if (IsWindowsServer()) { dwSessionId = sessionId == -1 ? GetSessions().First(s => s.State == WtsConnectState.WtsActive).SessionID : sessionId; } else { dwSessionId = sessionId == -1 ? WTSGetActiveConsoleSessionId() : sessionId; } if (WTSQueryUserToken((uint)dwSessionId, ref hToken)) { IntPtr pEnvBlock; if (CreateEnvironmentBlock(out pEnvBlock, hToken, false)) { var cmdLine = new StringBuilder(commandLine, 32768); ProcessInformation pi; if (CreateProcessAsUser(hToken, filename, cmdLine.ToString(), IntPtr.Zero, IntPtr.Zero, false, CreateUnicodeEnvironment, pEnvBlock, workingDirectory, ref si, out pi)) { WaitForSingleObject(pi.hProcess, Infinite); uint exitCode; GetExitCodeProcess(pi.hProcess, out exitCode); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return new RunAsResult { ProcessId = (int)pi.dwProcessId, ExitCode = (int)exitCode }; } throw new Win32Exception(); } throw new Win32Exception(); } throw new Win32Exception(); }
public static extern bool CreateProcessW(String applicationName, String commandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, Int32 dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, [MarshalAs(UnmanagedType.LPStruct)][In] Startupinfo lpStartupInfo, [MarshalAs(UnmanagedType.LPStruct)][In] ProcessInformation lpProcessInformation);
public static bool Launch() { if (Process.GetProcessesByName("Steam").Length == 0) { using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (var steamkey = hklm.OpenSubKey(@"SOFTWARE\Valve\Steam")) if (steamkey != null) { string SteamExe = (string)steamkey.GetValue("SteamExe"); if (SteamExe != null) { Process.Start(SteamExe); Thread.Sleep(2000); //wait is needed to allow steam to update and connect } } else { DialogResult dialogResult = MessageBox.Show("Steam is not installed!\n\nPlease install Steam to continue!.\n\nWant to do it now? ", "Steam Vailidation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dialogResult == DialogResult.Yes) { Process.Start("http://store.steampowered.com/about/"); Environment.Exit(1); } else { Environment.Exit(1); } } } String gamelocation = Properties.Settings.Default.ETS2Location; //allows a user who has trucksbook installed, run it before launching the game and connecting to MP if (Properties.Settings.Default.tbchk == true) { if (!File.Exists(Path.Combine(Properties.Settings.Default.tbpath, "TB Client.exe"))) { string error = "TrucksBook is not installed"; Loghandling.Logerror(error); Form1.Errorsound(); } var processes = Process.GetProcessesByName("TB Client"); if (processes.Length == 0 && File.Exists(Path.Combine(Properties.Settings.Default.tbpath, "TB Client.exe"))) { Process.Start(Path.Combine(Properties.Settings.Default.tbpath, "TB Client.exe")); Thread.Sleep(1500); //allows trucksbook to launch without the 'game running' error } } if (Properties.Settings.Default.singleplayer == true) { Process.Start(gamelocation + "\\bin\\win_x64\\eurotrucks2.exe"); Environment.Exit(0); } String binPath; String exe; String dll; String arguments = ""; String mplocation = Properties.Settings.Default.launcherpath; //Lets get our games straight if (Properties.Settings.Default.ETS2Location != null) { Environment.SetEnvironmentVariable("SteamGameId", "227300"); Environment.SetEnvironmentVariable("SteamAppID", "227300"); binPath = gamelocation + "\\bin\\win_x64"; exe = "\\eurotrucks2.exe"; dll = "\\core_ets2mp.dll"; arguments += " -64bit"; } else { return(false); //Invalid game, lets not do this } //Intialize variables 'n stuff ProcessInformation processInformation = default(ProcessInformation); Startupinfo startupinfo = default(Startupinfo); SecurityAttributes securityAttributes = default(SecurityAttributes); SecurityAttributes securityAttributes2 = default(SecurityAttributes); startupinfo.cb = Marshal.SizeOf(startupinfo); securityAttributes.nLength = Marshal.SizeOf(securityAttributes); securityAttributes2.nLength = Marshal.SizeOf(securityAttributes2); //Lets run the game! if (!CreateProcess(binPath + exe, arguments, ref securityAttributes, ref securityAttributes2, false, 4u, IntPtr.Zero, binPath, ref startupinfo, out processInformation)) { string error = "Failed to start game"; Loghandling.Logerror(error); return(false); } if (!Inject(processInformation.hProcess, "C:\\ProgramData\\TruckersMP" + dll)) { string error = "DLL injection failed"; Loghandling.Logerror(error); return(false); } ResumeThread(processInformation.hThread); return(true); }