public static BurntSushi Inject(Process process) { string?channelName = null; var server = RemoteHooking.IpcCreateServer <HookInterface>(ref channelName, WellKnownObjectMode.Singleton); // Get the full path to the assembly we want to inject into the target process var injectionLibrary = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "InjectionPayload.dll"); // inject into existing process RemoteHooking.Inject( process.Id, // ID of process to inject into injectionLibrary, // 32-bit library to inject (if target is 32-bit) injectionLibrary, // 64-bit library to inject (if target is 64-bit) channelName // the parameters to pass into injected library // ... ); return(new(server)); }
private static void Main(string[] args) { var TargetPID = 0; //TargetPID = System.Diagnostics.Process.GetProcessesByName("exefile")[0].Id; foreach (var exefile in Process.GetProcessesByName("exefile")) { ChannelName = null; TargetPID = exefile.Id; try { try { Config.Register( "A Aphack like demo application.", "Aphack.exe", "AphackInject.dll"); } catch (ApplicationException) { MessageBox.Show("This is an administrative task!", "Permission denied...", MessageBoxButtons.OK); Process.GetCurrentProcess().Kill(); } RemoteHooking.IpcCreateServer <AphackInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( TargetPID, "AphackInject.dll", "AphackInject.dll", ChannelName); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } } Console.ReadLine(); }
public static string InjectDll(string dllToInject, string targetExe, ref int targetPid, out string channelName, INotifyClient notifyClient) { channelName = null; RemoteHooking.IpcCreateServer <PostbackMessageHandler>(ref channelName, WellKnownObjectMode.SingleCall); var location = Assembly.GetExecutingAssembly().Location; var directoryName = Path.GetDirectoryName(location); var directoryIsNotNull = directoryName != null; string formattableString = null; if (directoryIsNotNull) { var injectionLibrary = Path.Combine(directoryName, dllToInject); if (File.Exists(injectionLibrary)) { if (string.IsNullOrEmpty(targetExe)) { RemoteHooking.Inject( targetPid, injectionLibrary, injectionLibrary, channelName); formattableString = $"Injected to process {targetPid}"; } else if (File.Exists(targetExe)) { RemoteHooking.CreateAndInject(targetExe, "", 0, InjectionOptions.DoNotRequireStrongName, injectionLibrary, injectionLibrary, out targetPid, channelName); formattableString = $"Created and injected process {targetPid}"; } } } if (notifyClient != null) { PostbackMessageHandler.RemoteHookerBasesToNotify.Add( new Tuple <INotifyClient, int>(notifyClient, targetPid)); } return(formattableString); }
public void Start() { if (_hookProxy != null) { return; } _hookProxy = new HookProxy(); _hookProxy.OnCreateProcess += OnOnCreateProcess; string channelName = null; RemoteHooking.IpcCreateServer(ref channelName, WellKnownObjectMode.SingleCall, _hookProxy); Log.Verbose("{channel} ipc channel created", channelName); RemoteHooking.Inject(_process.Id, hookDll, hookDll, channelName); Log.Verbose("Inject {dll} to {target} process({pid})", hookDll, _process.ProcessName, _process.Id); _downloadThread = new Thread(DownloadProc); _downloadThread.Start(); }
static void Main(string[] args) { int TargetPID; string targetExe = null; // Will contain the name of the IPC server channel string channelName = null; Process[] localByName = Process.GetProcessesByName("NotePad"); TargetPID = localByName[0].Id; RemoteHooking.IpcCreateServer <TestLib.FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); string injectionLibrary = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "TestLib.dll"); RemoteHooking.Inject( TargetPID, injectionLibrary, injectionLibrary, ChannelName); Console.WriteLine("Injected to process {0}", TargetPID); Console.WriteLine("<Press any key to exit>"); Console.ReadKey(); }
public bool OnCreateProcess(string appname, string commandline, string environment) { //ask user for interaction. Console.WriteLine("The process is trying to start a new process. This process will be sandboxed if Allowed. FilePath: {0}, allow?", (appname == commandline ? appname : "\"" + appname + "\", CommandLine: \"" + commandline + "\"")); string x = Console.ReadLine(); if (x == "y") { ProcessStartInfo b = new ProcessStartInfo(); b.Arguments = commandline; b.FileName = appname; b.WorkingDirectory = environment; Process w = Process.Start(b); RemoteHooking.Inject(w.Id, InjectionOptions.DoNotRequireStrongName, Program.currdir + "ThrInj.dll", Program.currdir + "ThrInj.dll", new Object[] { Program.ChannelName }); return(true); } else { return(false); } }
public bool TryInject() { RemoteHooking.InstallSupportDriver(); try { RemoteHooking.Inject(_targetProcessId, "Injector.dll", "Injector.dll", _channelName); if (InjectSuccess != null) { InjectSuccess(this, EventArgs.Empty); } return(true); } catch (Exception errorMsg) { if (InjectFailed != null) { InjectFailed(errorMsg.ToString()); } return(false); } }
public bool InjectDll() { Process[] psArray = Process.GetProcessesByName("XDE"); if (psArray.Length != 1) { return(false); } Int32 pid = psArray[0].Id; try { RemoteHooking.Inject(pid, "XDEHook.dll", "XDEHook.dll", channelName); } catch (Exception ExtInfo) { MessageBox.Show("There was an error while connecting to target:\r\n" + ExtInfo.ToString(), "Error"); return(false); } labelMsg.Text = "API hook status: Successfull, PID=" + pid.ToString(); return(true); }
public void Main(string processName) { var process = Process.GetProcessesByName(processName).Single(); string injectionLibrary = typeof(InjectEntryPoint).Assembly.Location; string channelName = null; RemoteHooking.IpcCreateServer <ServerInterface>( ref channelName, System.Runtime.Remoting.WellKnownObjectMode.Singleton); var parameter = new Parameter() { ChannelName = channelName }; try { Console.WriteLine($"Attemption to inject into process {process.Id}"); RemoteHooking.Inject( process.Id, injectionLibrary, injectionLibrary, parameter ); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("There was an error while injecting into target:"); Console.ResetColor(); Console.WriteLine(ex.ToString()); } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("<Press any key to exit>"); Console.ResetColor(); Console.ReadKey(); }
public void InjectLua(int ProcessID) { try { //create IPC log channell for injected dll, so it can log to the console string logChannelName = null; IpcServerChannel ipcLogChannel = RemoteHooking.IpcCreateServer <Logger>(ref logChannelName, WellKnownObjectMode.Singleton); var remoteLog = RemoteHooking.IpcConnectClient <Logger>(logChannelName); //inject dante.dll, pass in the log channel name RemoteHooking.Inject( ProcessID, "Dante.dll", "Dante.dll", logChannelName); //wait for the remote object channel to be created Thread.Sleep(200); //get remote object from channel name RemoteObject = RemoteHooking.IpcConnectClient <DanteInterface>(remoteLog.InjectedDLLChannelName); // If we're not using autologin we make sure that the LUA hook is off the way until we are logged in //RemoteObject.RegisterLuaHandler(); //RemoteObject.Patch(); // Set our codecave offset SetPatchOffset(Convert.ToUInt32( ProcessManager.Config.CustomParams.LuaCallback, 16)); Output.Instance.Log("Dante injected"); } catch (Exception ExtInfo) { Output.Instance.Log("There was an error while connecting to the target DLL"); Output.Instance.LogError(ExtInfo); } }
public MainWindow() { InitializeComponent(); try { RemoteHooking.IpcCreateServer <HookInterface>(ref _channelName, WellKnownObjectMode.SingleCall); string hookLib = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "AO.Hook.dll"); Process[] processes = Process.GetProcessesByName("AnarchyOnline"); foreach (Process process in processes) { RemoteHooking.Inject(process.Id, InjectionOptions.DoNotRequireStrongName, hookLib, hookLib, _channelName); } } catch (Exception e) { MessageBox.Show("Hooking into AO failed!\n" + e.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public bool Run() { if (TargetExePath != null) { RemoteHooking.CreateAndInject(TargetExePath, CommandLine, 0, InjectedLibPath, InjectedLibPath, out int pid, new Func <Dictionary <string, FileMapping> >(() => PuppetFiles)); TargetPid = pid; } else if (TargetPid > 0) { RemoteHooking.Inject(TargetPid, InjectedLibPath, InjectedLibPath, _channel); } return(false); }
/// <summary> /// Inject a DLL to target /// </summary> /// <param name="assemblyFile">x86 DLL</param> /// <param name="assemblyFile64">x64 DLL, if your target is 64bit program</param> /// <returns></returns> public int Inject(string assemblyFile, string assemblyFile64 = null) { try { _interface.SleepInterval = SleepInterval; _interface.IsBackgroundThread = IsBackgroundThread; if (RemoteHooking.IsX64Process(_pid)) { //Console.WriteLine("64bit program!"); } RemoteHooking.Inject(_pid, assemblyFile, assemblyFile64, _channelName); RegisterEvents(); return(_pid); } catch (Exception) { //FIXED: The Part Where He Kills You Eject(); return(0); } }
static void Main(string[] args) { Console.WriteLine("MapleStory Hooks"); Console.WriteLine(); Console.WriteLine("Input process name..."); string processName = Console.ReadLine(); bool lookingForProcess = true; while (lookingForProcess) { //Process[] processes = Process.GetProcessesByName("WvsLogin"); Process[] processes = Process.GetProcessesByName(processName); if (processes.Length > 0) { Console.WriteLine("Found process."); int pid = processes[0].Id; string path = @"MapleStoryHooks.dll"; string path2 = @"MapleStoryHooks.exe"; Config.Register("Maplestory hook", path, path2); RemoteHooking.IpcCreateServer <MapleStoryHookInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject(pid, path, path, ChannelName); lookingForProcess = false; } else { Console.WriteLine("Cannot find process."); Thread.Sleep(500); } } Console.ReadLine(); }
/// <summary> /// Inject the "Injected" library into Street Fighter. /// </summary> public void Inject() { if (string.IsNullOrEmpty(channelName)) { Process[] procs = Process.GetProcessesByName("SSFIV"); int sf4Pid = procs[0].Id; SF4Interface = new SF4Interface(); RemoteHooking.IpcCreateServer <SF4Interface>( ref channelName, WellKnownObjectMode.Singleton, SF4Interface, new[] { WellKnownSidType.LocalSid }); RemoteHooking.Inject( sf4Pid, InjectionOptions.DoNotRequireStrongName, "FrameTrapped.Injected.dll", "FrameTrapped.Injected.dll", channelName); } }
private static void InjectProcess(string networkId, int processId) { var injectorAddress = Assembly.GetExecutingAssembly().Location; var tries = 0; while (true) { try { Console.WriteLine("Trying to inject process #{0}.", processId); RemoteHooking.Inject( processId, injectorAddress, injectorAddress, networkId, injectorAddress, CommandLineOptions.Default.Delay, CommandLineOptions.Default.ChangeWindowTitle, CommandLineOptions.Default.Debug ); return; } catch { if (tries < 3) { tries++; Thread.Sleep(1000); } else { throw; } } } }
static void Main(string[] args) { Int32 TargetPID = 0; if ((args.Length != 1) || !Int32.TryParse(args[0], out TargetPID)) { Console.WriteLine(); Console.WriteLine("Usage: FileMon %PID%"); Console.WriteLine(); return; } try { Config.Install(Environment.CurrentDirectory + "\\EasyHook.dll"); Config.Register( "A FileMon like demo application.", "FileMon.exe", "FileMonInject.dll"); RemoteHooking.IpcCreateServer <FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( TargetPID, InjectionOptions.None, "FileMonInject.dll", "FileMonInject.dll", ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
private static void Main(string[] args) { try { args = new string[4]; args[0] = @"C:/Program Files (x86)/CCP/EVE/bin"; args[1] = @"setting.ini"; args[2] = @"C:/Users/Arjen/Documents/EvE Programming/Adapteve/Adapteve/Adapteve/bin/Debug/QuestorDLL.DLL"; args[3] = @"1"; if (args.Count() < 4) { Console.WriteLine("Usage: Adapteve.exe [ExeFile-path] [IniFile] [Questor-DLL] [Questor-Parameters]"); Console.ReadLine(); return; } var exefilePath = Utility.GetExefilePath(args[0]); var iniFile = Utility.VerifyIniFile(args[1]); var dll = Directory.GetCurrentDirectory() + "/AdapteveDLL.dll"; var qDll = args[2]; var qParam = args[3]; RemoteHooking.CreateAndInject(exefilePath, "", (int)InjectionOptions.Default, dll, dll, out pid, "", iniFile, qDll, qParam); Thread.Sleep(500); RemoteHooking.Inject(pid, qDll, qDll, qParam); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
public void InjectControllerIntoProcess(Process p) { if (!Valve.VR.OpenVR.IsHmdPresent()) { throw new PocketStrafeOutputDeviceException("No HMD was found."); } try { log.Info(" Injecting " + _InjectDll + " into " + p.ProcessName + " " + "(" + p.Id + ")"); RemoteHooking.Inject( p.Id, InjectionOptions.DoNotRequireStrongName, _InjectDll, _InjectDll, _ChannelName); for (int i = 0; i < 20; i++) { if (Iface.Installed) { ResourceSoundPlayer.TryToPlay(Properties.Resources.beep_good); log.Info("Successfully injected!"); return; } System.Threading.Thread.Sleep(300); } throw new PocketStrafeOutputDeviceException("Connecting hook timed out. Make sure Steam VR is running."); } catch (Exception e) { ResourceSoundPlayer.TryToPlay(Properties.Resources.beep_bad); log.Error(" EasyHook Error: " + e.Message); log.Error(e); throw new PocketStrafeOutputDeviceException(e.Message); } }
public static void Entry() { string channelName = null; var lcGoLProc = GetProcesses().FirstOrDefault(p => "Lara Croft and the Guardian of Light".Equals(p.GetApplicationName(), StringComparison.OrdinalIgnoreCase)); if (lcGoLProc != null) { // Setup Communication Server RemoteHooking.IpcCreateServer <LCGoLOverlayProcess.ServerInterface>(ref channelName, System.Runtime.Remoting.WellKnownObjectMode.Singleton); string thisPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (!string.IsNullOrWhiteSpace(thisPath)) { string injectionLibPath = Path.Combine(thisPath, "LCGoLOverlayProcess.dll"); try { Console.WriteLine("Attempting to inject into process {0}", lcGoLProc.Id); RemoteHooking.Inject(lcGoLProc.Id, injectionLibPath, injectionLibPath, channelName, lcGoLProc.Id); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("There was an error while injecting into target:"); Console.ResetColor(); Console.WriteLine(e.ToString()); } } } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("<Press any key to exit>"); Console.ResetColor(); Console.ReadKey(); }
private bool InstallHookTo_Process() { try { string injectionLibrary = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "CaxaInject.dll"); RemoteHooking.IpcCreateServer <HookDealWith>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( pID, InjectionOptions.Default, injectionLibrary, injectionLibrary, ChannelName ); } catch (Exception ex) { Debug.Print(ex.ToString()); return(false); } return(true); }
static void Main(string[] args) { try { Config.Register( "A FileMon like demo application.", "FileMon.exe", "FileMonInject.dll"); RemoteHooking.IpcCreateServer <FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( Int32.Parse(args[0]), "FileMonInject.dll", "FileMonInject.dll", ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
public static void Hook(int processId) { try { string channelName = null; RemoteHooking.IpcCreateServer <ServerInterface>(ref channelName, WellKnownObjectMode.Singleton); var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (string.IsNullOrEmpty(currentPath)) { throw new InvalidOperationException(); } var injectionLibrary = Path.Combine(currentPath, "DefaultTerminal.Hook.dll"); RemoteHooking.Inject(processId, injectionLibrary, injectionLibrary, channelName); Console.WriteLine($@"New Hook Success : {processId}"); } catch (Exception ex) { Console.WriteLine($@"Exception : {ex.Message}"); } }
void Attach(string procname, string fn) { procname = procname.ToLower(); Process process = null; foreach (Process proc in Process.GetProcesses()) { if (procname == proc.ProcessName.ToLower()) { process = proc; break; } } StreamReader sr = new StreamReader(File.OpenRead(fn)); string code = sr.ReadToEnd(); RemoteHooking.Inject( process.Id, "Obj/EIInject.dll", "Obj/EIInject.dll", code ); }
public void Inject(int processId) { try { string channelName = null; RemoteHooking.IpcCreateServer(ref channelName, WellKnownObjectMode.Singleton, ServerInterface); var injectionLibrary = Path.Combine(Directory.GetCurrentDirectory(), "Hook.dll"); RemoteHooking.Inject( processId, injectionLibrary, injectionLibrary, channelName ); Thread.Sleep(1000); } catch (Exception e) { MessageBox.Show(e.ToString()); } }
static void Main(string[] args) { version = AppVersion(); version_short = AppVersionShort(); Console.WriteLine("Starting .altnet DNS Lookup Intercept, v" + version + "."); Int32 TargetPID = 0; // Check software version. int rand = RandomNumber(100000, 999999); string vurl = "http://" + AltNetHost + "/alternatenet/injector-version.php?v=" + version_short + "&r=" + rand.ToString(); HttpWebResponse response = null; Stream dataStream = null; StreamReader reader = null; try { Console.WriteLine("Checking injector software version."); HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(vurl); myReq.UserAgent = "Alternatenet/1.0 version check +http://sherpoint.mooo.com:8888/alternatenet/"; response = (HttpWebResponse)myReq.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); if (responseFromServer.IndexOf("!OK!") >= 0) { // Software does not need updating. // NOP, carry on. Console.WriteLine("OK, the DLL injector software is up-to-date."); } else if (responseFromServer.IndexOf("!UPDATE!") >= 0) { // Software needs updating. Quit the program to make the user update. // We need this as we may have changed name server domain name; etc. Console.WriteLine("You need to update the DLL injector software\r\nat sherpoint.mooo.com/alternatenet/"); Console.WriteLine("Press control-c to exit the console."); Console.ReadLine(); return; } else { Console.WriteLine("Software version check: " + responseFromServer); } } else { Console.WriteLine("Software version check: Server response: " + response.StatusDescription); } } catch (System.Net.WebException wex) { Console.WriteLine("Software version check: Error: " + wex.Message); try { reader.Close(); } catch { // NOP } try { dataStream.Close(); } catch { // NOP } try { response.Close(); } catch { // NOP } } Console.WriteLine("Collecting open processes."); Process [] localByName = Process.GetProcesses(); try { bool anyfound = false; bool browserfound = false; string ProcessName = ""; foreach (Process p in localByName) { anyfound = true; ProcessName = p.ProcessName; // Console.WriteLine("'" + ProcessName + "','" + BrowserProcessName + "'"); if (ProcessName == AltNetBrowserProcessName) { // Try "firefox" or "chrome". // Yahoo! Firefox works. // OK, so now we can intercept GetAddrInfoW. // If it's a .altnet address, do our own lookup // and pass that back to Firefox. browserfound = true; TargetPID = p.Id; Console.WriteLine("Found open web browser ('" + AltNetBrowserProcessName + "') process."); break; } } if (anyfound == false) { Console.WriteLine("No processes running.\r\nYou need to launch the browser ('" + AltNetBrowserProcessName + "') first."); Console.WriteLine("Press control-c to exit the console."); Console.ReadLine(); return; } if (browserfound == false) { Console.WriteLine("Browser named in configuration file is not running.\r\nYou need to launch the browser ('" + AltNetBrowserProcessName + "') first."); Console.WriteLine("Press control-c to exit the console."); Console.ReadLine(); return; } } catch (Exception ex) { Console.WriteLine("Exception in process enumeration:\r\n{0}", ex.ToString()); Console.WriteLine("Press control-c to exit the console."); Console.ReadLine(); return; } try { Config.Register( "An app to intercept DNS lookups for .altnet domains.", "DNSInterceptConsole.exe", "DNSIntercept.dll"); RemoteHooking.IpcCreateServer <InterceptInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( TargetPID, "DNSIntercept.dll", "DNSIntercept.dll", ChannelName); Console.WriteLine("Press control-c to exit the console."); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); Console.WriteLine("Press control-c to exit the console."); Console.ReadLine(); } finally { // NOP. } }
private HookManager.ProcessInfo AttachCurrentProcess(bool force = true) { try { Process currentProcess = GetForegroundProcess(); if (currentProcess == null) { if (force == true) { ScreenshotManager_OnScreenshotDebugMessage(0, "No Foreground found"); } return(null); } HookManager.ProcessInfo pInfo = HookManager.GetHookedProcess(currentProcess); // Skip if the process is already hooked (and we want to hook multiple applications) if (pInfo == null) { if (force == false & !autoAttach.Contains(currentProcess.ProcessName)) { return(null); } List <String> modules = GetProcessModules(currentProcess); bool hasDx = false; foreach (String module in supportedModules) { hasDx = (hasDx | modules.Contains(module)); } if (!hasDx) { ScreenshotManager_OnScreenshotDebugMessage(0, "No DX found"); return(null); } // Keep track of hooked processes in case more than one needs to be hooked pInfo = HookManager.AddHookedProcess(currentProcess); // Inject DLL into target process try { RemoteHooking.Inject( currentProcess.Id, InjectionOptions.Default, typeof(ScreenshotInject.ScreenshotInjection).Assembly.Location, //"ScreenshotInject.dll", // 32-bit version (the same because AnyCPU) could use different assembly that links to 32-bit C++ helper dll typeof(ScreenshotInject.ScreenshotInjection).Assembly.Location, //"ScreenshotInject.dll", // 64-bit version (the same because AnyCPU) could use different assembly that links to 64-bit C++ helper dll // the optional parameter list... ChannelName, // The name of the IPC channel for the injected assembly to connect to Direct3DVersion.AutoDetect.ToString(), // The direct3DVersion used in the target application false //cbDrawOverlay.Checked ); } catch (Exception e) { ScreenshotManager_OnScreenshotDebugMessage(currentProcess.Id, e.GetType().FullName + ": " + e.Message); } ScreenshotManager_OnScreenshotDebugMessage(currentProcess.Id, "Injected "); } return(pInfo); } catch (Exception e) { ScreenshotManager_OnScreenshotDebugMessage(0, e.ToString()); return(null); } }
static void Main(string[] args) { #if !DEBUG //check work path var filePath = AppDomain.CurrentDomain.BaseDirectory; var workPath = Directory.GetCurrentDirectory() + @"\"; if (filePath != workPath) { Directory.SetCurrentDirectory(filePath); } #endif //init Process gameProcess; var pid = -1; if (args.Length >= 1) { try { var argPid = args[0]; if (argPid.StartsWith("0x")) { pid = Convert.ToInt32(args[0], 16); } else { pid = Convert.ToInt32(args[0]); } } catch { throw new Exception("the first argument should be the pid of ffxiv game"); } } try { if (pid == -1) { gameProcess = Process.GetProcessesByName("ffxiv_dx11")[0]; } else { gameProcess = Process.GetProcessById(pid); if (gameProcess.ProcessName != "ffxiv_dx11") { throw new Exception("the pid is invalid"); } } } catch (Exception e) { throw e; } var lang = ClientLanguage.ChineseSimplified; if (args.Length >= 2) { try { lang = (ClientLanguage)Convert.ToInt32(args[1]); } catch { throw new Exception("the second argument should be the language enum"); } } #if !DEBUG //检查是否已经被注入 foreach (ProcessModule module in gameProcess.Modules) { if (module.ModuleName == "EasyHook64.dll") { Console.WriteLine($"gameProcess {gameProcess.Id} has been injected"); Environment.Exit(0); } } #endif // File check var libPath = Path.GetFullPath("Dalamud.dll"); var pluginPath = Path.GetDirectoryName(libPath); if (!File.Exists(libPath)) { Console.WriteLine("can not find dalamud.dll"); return; } var xivLauncherPath = Environment.ExpandEnvironmentVariables(@"%appdata%");//国际服only var loadPath = lang == ClientLanguage.Japanese ? xivLauncherPath : pluginPath; //构建command line var command = new DalamudStartInfo { WorkingDirectory = pluginPath, ConfigurationPath = loadPath + @"\XIVLauncher\dalamudConfig.json", PluginDirectory = loadPath + @"\XIVLauncher\installedPlugins", DefaultPluginDirectory = loadPath + @"\XIVLauncher\devPlugins", AssetDirectory = pluginPath + @"\XIVLauncher\dalamudAssets", GameVersion = GetGameVersion(gameProcess), Language = lang }; //clean dalamud log Task.Run(() => CleanDalamudLog()); // Inject try { Thread.Sleep(500); RemoteHooking.Inject(gameProcess.Id, InjectionOptions.DoNotRequireStrongName, libPath, libPath, command); } catch (Exception) { throw; } }
// ReSharper disable once TooManyArguments private bool OnCreateProcess( IntPtr applicationName, IntPtr commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment, IntPtr currentDirectory, IntPtr startupInfo, out ProcessInformation processInformation, bool isUnicode) { var resultValue = isUnicode ? UnManaged.Process.CreateProcessW( applicationName, commandLine, processAttributes, threadAttributes, inheritHandles, creationFlags, environment, currentDirectory, startupInfo, out processInformation ) : UnManaged.Process.CreateProcessA( applicationName, commandLine, processAttributes, threadAttributes, inheritHandles, creationFlags, environment, currentDirectory, startupInfo, out processInformation ); if (!resultValue) { return(false); } if (processInformation.ProcessId <= 0) { return(true); } var processId = processInformation.ProcessId; DebugMessage(nameof(OnCreateProcess), "A new process with identification number of #{0} is created.", processId); new Thread(() => { Thread.Sleep(InjectionDelay); var tries = 1; while (true) { try { RemoteHooking.Inject( processId, InjectionGuessAddress, InjectionGuessAddress, AdapterId, InjectionGuessAddress, InjectionDelay, !string.IsNullOrWhiteSpace(LogPath) ); DebugMessage(nameof(OnCreateProcess), "Process #{0} injected with the guest code.", processId); return; } catch { if (tries < 3) { tries++; Thread.Sleep(1000); continue; } DebugMessage(nameof(OnCreateProcess), "Failed to inject the guest code to process #{0}.", processId); return; } } }).Start(); return(true); }
public static bool Attach(uint pid, OptionsData options, bool isRazor, out int index) { lock (myLock) { Process p = null; index = -1; try { Thread.Sleep(2000); p = Process.GetProcessById((int)pid); p.EnableRaisingEvents = true; p.Exited += new EventHandler(UOM.OnClientExit); ClientInfo ci = new ClientInfo(p); Memory.MemoryInit(ci); if (ci.IsValid) { ci.InstallMacroHook(); } else { return(false); } if (!isRazor && options.PatchClientEncryptionUOM) { if (!ClientPatcher.PatchEncryption(p.Handle)) { MessageBox.Show(Strings.Errorpatchingclientencryption, Strings.Error); } } if (ci.DateStamp < 0x4AA52CC4 && options.PatchStaminaCheck) { if (!ClientPatcher.PatchStaminaCheck(p.Handle)) { MessageBox.Show(Strings.Errorpatchingstaminacheck, Strings.Error); } } if (options.PatchAlwaysLight) { if (!ClientPatcher.PatchLight(p.Handle)) { MessageBox.Show(Strings.Errorwithalwayslightpatch, Strings.Error); } } if (options.PatchGameSize) { if (!ClientPatcher.SetGameSize(p.Handle, options.PatchGameSizeWidth, options.PatchGameSizeHeight)) { //Silently fail for now as this will fail on UOSteam. //MessageBox.Show(Strings.Errorsettinggamewindowsize); } } int instance; if (!ClientInfoCollection.AddClient(ci, out instance)) { throw new ApplicationException(String.Concat(Strings.Unknownerror, ": ClientInfoCollection.Add.")); } ci.Instance = instance; index = instance; Macros.Macro.ChangeServer(instance, options.Server, options.Port); Thread.Sleep(500); RemoteHooking.Inject(p.Id, Path.Combine(UOM.StartupPath, "clienthook.dll"), Path.Combine(UOM.StartupPath, "clienthook.dll"), UOM.ServerName); } catch (Exception e) { Utility.Log.LogMessage(e); MessageBox.Show(Strings.Errorinjectingdll, Strings.Error); try { if (p != null) { p.Kill(); } } catch (Win32Exception) { } catch (InvalidOperationException) { } return(false); } UOM.SetStatusLabel(Strings.Attachedtoclient); return(true); } }