static void Main(string[] args) { try { /*Config.Register( * "ThrInj", * currdir + "ThrInj_Con.exe", * currdir + "ThrInj.dll");*/ //args = new string[] { "TestApp.exe" }; RemoteHooking.IpcCreateServer <RemoteMon>( ref ChannelName, WellKnownObjectMode.Singleton); int processid; //RemoteHooking.CreateAndInject(args[0], "", 0, currdir + "ThrInj.dll", currdir + "ThrInj.dll", out processid, ChannelName); ProcessStartInfo f = new ProcessStartInfo(); f.FileName = args[0]; Process x = Process.Start(f); RemoteHooking.Inject(x.Id, InjectionOptions.DoNotRequireStrongName, currdir + "ThrInj.dll", currdir + "ThrInj.dll", new Object[] { ChannelName }); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting " + "to target:\r\n{0}", ExtInfo.ToString()); Console.ReadLine(); } while (true) { Thread.Sleep(1000); } }
private void hook_Click(object sender, RoutedEventArgs e) { String ChannelName = null; Int32 TargetPID = 0; Process[] procs = Process.GetProcessesByName("exefile"); if (procs.Length == 0) { Log.log("Could not find EVE (exefile.exe)"); return; } try { TargetPID = procs[0].Id; RemoteHooking.IpcCreateServer <HookInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); string injectionLibrary = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "HookInject.dll"); RemoteHooking.Inject( TargetPID, injectionLibrary, injectionLibrary, ChannelName); // SharedCache\tq var path = Path.GetDirectoryName(Path.GetDirectoryName(procs[0].MainModule.FileName)); var pyPath = path + "\\code.ccp;" + path + "\\bin64"; // Copy object DB var dbFile = "mapObjects.db"; var dbPath = path + "\\bin64\\staticdata\\" + dbFile; if (!File.Exists(dbFile) || File.GetLastWriteTime(dbFile) != File.GetLastWriteTime(dbPath)) { File.Copy(dbPath, dbFile, true); } // Load Python var pyDll = LoadLibrary(path + "\\bin64\\python27.dll"); if (pyDll != IntPtr.Zero) { var Py_GetPathWData = GetProcAddress(pyDll, "Py_GetPathWData"); var rawPath = Marshal.AllocHGlobal(pyPath.Length * 2 + 2); var pathBytes = Encoding.Unicode.GetBytes(pyPath); Marshal.Copy(pathBytes, 0, rawPath, pathBytes.Length); Marshal.WriteIntPtr(Py_GetPathWData, rawPath); pythonLoaded = true; } else { Log.log("Failed to load " + path + "\\bin64\\python27.dll"); } } catch (Exception ExtInfo) { Log.log("-- error while connecting to target --"); Log.log(ExtInfo.ToString(), false); Log.log("-- /error while connecting to target --"); } }
public static int Main(String inParam) { if (inParam == null) { return(0); } var ptr = (IntPtr)Int64.Parse(inParam, NumberStyles.HexNumber); var connection = HostConnectionData.LoadData(ptr); if (connection.State != HostConnectionData.ConnectionState.Valid) { return((int)connection.State); } // Adjust host PID in case of WOW64 bypass and service help... connection.UnmanagedInfo.m_HostPID = connection.RemoteInfo.HostPID; try { // Prepare parameter array. var paramArray = new object[1 + connection.RemoteInfo.UserParams.Length]; // The next type cast is not redundant because the object needs to be an explicit IContext // when passed as a parameter to the IEntryPoint constructor and Run() methods. paramArray[0] = (RemoteHooking.IContext)connection.UnmanagedInfo; for (var i = 0; i < connection.RemoteInfo.UserParams.Length; i++) { paramArray[i + 1] = connection.RemoteInfo.UserParams[i]; } // Note: at this point all but the first parameter are still binary encoded. // Load the user library and initialize the IEntryPoint. return(LoadUserLibrary(connection.RemoteInfo.UserLibraryName, connection.RemoteInfo.UserLibrary, paramArray, connection.HelperInterface)); } catch (Exception ExtInfo) { Config.PrintWarning(ExtInfo.ToString()); return(-1); } finally { if (_connectedChannels.Contains(connection.RemoteInfo.ChannelName)) { _connectedChannels.Remove(connection.RemoteInfo.ChannelName); } } }
/// <summary> /// Loads <see cref="HostConnectionData" /> from the <see cref="IntPtr" /> specified. /// </summary> /// <param name="unmanagedInfoPointer"></param> public static HostConnectionData LoadData(IntPtr unmanagedInfoPointer) { var data = new HostConnectionData { _state = ConnectionState.Valid, _unmanagedInfo = new REMOTE_ENTRY_INFO() }; try { // Get the unmanaged data Marshal.PtrToStructure(unmanagedInfoPointer, data._unmanagedInfo); using (Stream passThruStream = new MemoryStream()) { var passThruBytes = new byte[data._unmanagedInfo.UserDataSize]; var format = new BinaryFormatter(); // Workaround for deserialization when not using GAC registration format.Binder = new AllowAllAssemblyVersionsDeserializationBinder(); Marshal.Copy(data._unmanagedInfo.UserData, passThruBytes, 0, data._unmanagedInfo.UserDataSize); passThruStream.Write(passThruBytes, 0, passThruBytes.Length); passThruStream.Position = 0; data._remoteInfo = (ManagedRemoteInfo)format.Deserialize(passThruStream); } // Connect the HelperServiceInterface data._helperInterface = RemoteHooking.IpcConnectClient <HelperServiceInterface>(data._remoteInfo.ChannelName); // Ensure that the connection is working... data._helperInterface.Ping(); if (!_connectedChannels.Contains(data._remoteInfo.ChannelName)) { _connectedChannels.Add(data._remoteInfo.ChannelName); return(new HostConnectionData { _state = ConnectionState.NoChannel }); } } catch (Exception ExtInfo) { Config.PrintError(ExtInfo.ToString()); return(new HostConnectionData { _state = ConnectionState.Invalid }); } return(data); }
// 初始化Entry,并非初始化SDK,将unity的响应 对象以及函数 传给SDK,并从SDK中获取渠道ID public static int InitEntry() { //Debug.Log("InitEntry"); msChannel = ExtInfo.GetChannel(); msChanTag = msChannel; Debug.Log("InitEntry:" + msChannel); // 非编辑器模式且是真机模式下才能进行 if (msChannel != 0 && Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsEditor) { // SDKEntry msChanTag = _InitEntry(SDKEntry.msUnityGoName, SDKEntry.msUnitySDKApiFun); msSDKApiCB = (apiName, retJson) => { m_sdkCallFun.LazyCall(apiName, retJson); }; } return(msChannel); }
public static int Main(string inParam) { if (inParam == null) { return(0); } var ptr = (IntPtr)Int64.Parse(inParam, System.Globalization.NumberStyles.HexNumber); var connection = HostConnectionData.LoadData(ptr); if (connection.State != HostConnectionData.ConnectionState.Valid) { return((int)connection.State); } // Adjust host PID in case of WOW64 bypass and service help... connection.UnmanagedInfo.m_HostPID = connection.RemoteInfo.HostPID; try { // Prepare parameter array. var paramArray = new object[1 + connection.RemoteInfo.UserParams.Length]; paramArray[0] = (RemoteHooking.IContext)connection.UnmanagedInfo; for (int i = 0; i < connection.RemoteInfo.UserParams.Length; i++) { paramArray[i + 1] = connection.RemoteInfo.UserParams[i]; } /// Load the user library and initialize the IEntryPoint. return(LoadUserLibrary(connection.RemoteInfo.UserLibrary, paramArray, connection.HelperInterface)); } catch (Exception ExtInfo) { Config.Log.Warning(ExtInfo.ToString()); return(-1); } finally { if (_connectedChannels.Contains(connection.RemoteInfo.ChannelName)) { _connectedChannels.Remove(connection.RemoteInfo.ChannelName); } } }
/// <summary> /// Returns true if APIKeyBase instances are equal /// </summary> /// <param name="input">Instance of APIKeyBase to be compared</param> /// <returns>Boolean</returns> public bool Equals(APIKeyBase input) { if (input == null) { return(false); } return (( RetCode == input.RetCode || (RetCode != null && RetCode.Equals(input.RetCode)) ) && ( RetMsg == input.RetMsg || (RetMsg != null && RetMsg.Equals(input.RetMsg)) ) && ( ExtCode == input.ExtCode || (ExtCode != null && ExtCode.Equals(input.ExtCode)) ) && ( ExtInfo == input.ExtInfo || (ExtInfo != null && ExtInfo.Equals(input.ExtInfo)) ) && ( Result == input.Result || Result != null && Result.SequenceEqual(input.Result) ) && ( TimeNow == input.TimeNow || (TimeNow != null && TimeNow.Equals(input.TimeNow)) )); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (RetCode != null) { hashCode = hashCode * 59 + RetCode.GetHashCode(); } if (RetMsg != null) { hashCode = hashCode * 59 + RetMsg.GetHashCode(); } if (ExtCode != null) { hashCode = hashCode * 59 + ExtCode.GetHashCode(); } if (ExtInfo != null) { hashCode = hashCode * 59 + ExtInfo.GetHashCode(); } if (Result != null) { hashCode = hashCode * 59 + Result.GetHashCode(); } if (TimeNow != null) { hashCode = hashCode * 59 + TimeNow.GetHashCode(); } return(hashCode); } }
static void Main(string[] args) { int i = 0; foreach (var item in Process.GetProcessesByName("ViniSandbox")) { i = item.Id; } try { Config.Register( "Teste", "MutexMonitor.exe", "MutexMonitorInject.dll"); RemoteHooking.IpcCreateServer <MutexMonitorInterface>( ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( //Int32.Parse(args[0]), i, "MutexMonitorInject.dll", "MutexMonitorInject.dll", ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting " + "to target:\r\n{0}", ExtInfo.ToString()); } /* Microsoft.Win32.SafeHandles.SafeFileHandle h; * string dEntry = "\\"; * ArrayList entries = new ArrayList(); * entries.Add(dEntry); * while (entries.Count != 0) * { * foreach (String entry in entries) * { * var attr = new Win.OBJECT_ATTRIBUTES(entry, 0); * var st = Win.NtOpenDirectoryObject(out h, 1, ref attr); * if (st < 0) * { * h.Dispose(); * entries.Remove(entry); * break; * } * * var bufsz = 1024; * var buf = Marshal.AllocHGlobal(bufsz); * uint context = 0, len; * while (true) * { * st = Win.NtQueryDirectoryObject(h, buf, bufsz, true, context == 0, ref context, out len); * if (st < 0) * { * entries.Remove(entry); * Marshal.FreeHGlobal(buf); * h.Dispose(); * break; * } * var odi = (Win.OBJECT_DIRECTORY_INFORMATION) * Marshal.PtrToStructure(buf, typeof(Win.OBJECT_DIRECTORY_INFORMATION)); * if (Convert.ToString(odi.TypeName) == "Mutant") * { * Console.WriteLine("0x{0:X2}:{1,-25}{2}", context, odi.TypeName, odi.Name); * } * if (Convert.ToString(odi.TypeName) == "Directory") * { * if (entry == "\\") * { * entries.Add(entry + Convert.ToString(odi.Name)); * } * else * { * entries.Add(entry + "\\" + Convert.ToString(odi.Name)); * } * } * } * break; * } * }*/ }
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 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); }
static void Main(string[] args) { try { int unityPid; try { Config.Register("D3DCompile Debug Flag Injector", "D3DCompileInjectorHost.exe", "D3DCompileInjectedDll.dll"); } catch (ApplicationException) { MessageBox.Show("Must run as admin!", "Permission denied...", MessageBoxButtons.OK); System.Diagnostics.Process.GetCurrentProcess().Kill(); } //while (true) //{ // Process[] procs = Process.GetProcessesByName("TestD3DPInvoke"); // if (procs.Length == 0) // { // //Thread.Sleep(500); // continue; // } // unityPid = procs[0].Id; // break; //} { ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Unity4.3\Editor\Data\Tools\CgBatch.exe"); startInfo.Arguments = @"""Temp/CgBatchInput.shader"" ""Assets/VSM"" ""C:/Program Files (x86)/Unity4.3/Editor/Data/CGIncludes"" ""Temp/CgBatchOutput.shader"" ""-d3d11_9x"""; startInfo.WorkingDirectory = @"C:\Users\ikrima\src\KnL\Kiten\StaticShadowMap"; startInfo.UseShellExecute = false; var cgBatchProcess = Process.Start(startInfo); unityPid = cgBatchProcess.Id; } RemoteHooking.IpcCreateServer <D3DCompileInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( unityPid, InjectionOptions.DoNotRequireStrongName, "D3DCompileInjectedDll.dll", "D3DCompileInjectedDll.dll", ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
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 { //try //{ // Config.Register( // "A FileMon like demo application.", // "FileMon.exe", // "FileMonInject.dll"); //} //catch (ApplicationException) //{ // MessageBox.Show("This is an administrative task!", "Permission denied...", MessageBoxButtons.OK); // System.Diagnostics.Process.GetCurrentProcess().Kill(); //} RemoteHooking.IpcCreateServer <FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( TargetPID, "FileMonInject.dll", "FileMonInject.dll", GetSharedAssemblies(), ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.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. } }
static void Main(string[] args) { //#if DEBUG //#else var configFile = "Localization.json"; if (!File.Exists(configFile)) { File.WriteAllText(configFile, Newtonsoft.Json.JsonConvert.SerializeObject(FileMonInterface.dict, Newtonsoft.Json.Formatting.Indented)); } FileMonInterface.dict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, Dictionary <string, string> > >(File.ReadAllText(configFile)); //#endif var targetExe = "notepad.exe"; foreach (var key in FileMonInterface.dict.Keys) { targetExe = key; break; } Int32 TargetPID = 0; Process p = null; foreach (var process in Process.GetProcesses()) { if ("NOTEPAD" == process.ProcessName.ToUpper()) { p = process; TargetPID = process.Id; break; } } if (0 == TargetPID) { p = Process.Start(targetExe); TargetPID = p.Id; } try{ Config.Register( "A FileMon like demo application.", "FileMon.exe", "FileMonInject.dll"); RemoteHooking.IpcCreateServer <FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( TargetPID, "FileMonInject.dll", "FileMonInject.dll", ChannelName); while (true) { Thread.Sleep(1); if (null != p) { if (p.HasExited) { break; } } } Console.Write("done"); Thread.Sleep(100); //Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); Console.ReadLine(); } }
static void Main(string[] args) { _interface.keys = new List <Keys>(); if ((args.Length != 3)) { Console.WriteLine(); Console.WriteLine("Usage: D3DTextureLoggerClient.exe %EXENAME% %D3DMODULE% %D3DXMODULE"); Console.WriteLine(); return; } exeName = args[0]; try { try { Console.WriteLine(args[0]); _interface.exe = args[0].Substring(0, args[0].Length - 3); d3d9Util = new D3DHookingLibrary.D3DFuncLookup(args[0], args[1]); } catch (ApplicationException) { System.Diagnostics.Process.GetCurrentProcess().Kill(); } Application.Run(new Form1()); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
static void Main(string[] args) { Int32 TargetPID = 0; if ((args.Length != 1) || !Int32.TryParse(args[0], out TargetPID)) { Console.WriteLine(); Console.WriteLine("Usage: MalMonitor.exe %PID%"); Console.WriteLine(); return; } try { try { //absolute path /* * Config.Register( * "A MalMonitor like demo application.", * "D:\\Source\\MalMonInject\\bin\\Release\\MalMonitor.exe", * "D:\\Source\\MalMonInject\\bin\\Release\\MalMonInject.dll"); */ //relative path Config.Register( "A MalMonitor like demo app", "MalMonitor.exe", "MalMonInject.dll"); } catch (ApplicationException) { Console.WriteLine("file not found!...."); System.Diagnostics.Process.GetCurrentProcess().Kill(); } RemoteHooking.IpcCreateServer <MonitorInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( TargetPID, "MalMonInject.dll", "MalMonInject.dll", ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
static void Main(string[] args) { Int32 TargetPID = 0; string targetExe = null; // Load the parameter while ((args.Length != 1) || !Int32.TryParse(args[0], out TargetPID) || !File.Exists(args[0])) { if (TargetPID > 0) { break; } if (args.Length != 1 || !File.Exists(args[0])) { Console.WriteLine(); Console.WriteLine("Usage: FileMon %PID%"); Console.WriteLine(" or: FileMon PathToExecutable"); Console.WriteLine(); Console.Write("Please enter a process Id or path to executable: "); args = new string[] { Console.ReadLine() }; if (String.IsNullOrEmpty(args[0])) { return; } } else { targetExe = args[0]; break; } } try { RemoteHooking.IpcCreateServer <FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall); string injectionLibrary = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "FileMonInject.dll"); if (String.IsNullOrEmpty(targetExe)) { RemoteHooking.Inject( TargetPID, injectionLibrary, injectionLibrary, ChannelName); Console.WriteLine("Injected to process {0}", TargetPID); } else { RemoteHooking.CreateAndInject(targetExe, "", 0, InjectionOptions.DoNotRequireStrongName, injectionLibrary, injectionLibrary, out TargetPID, ChannelName); Console.WriteLine("Created and injected process {0}", TargetPID); } Console.WriteLine("<Press any key to exit>"); Console.ReadKey(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); Console.WriteLine("<Press any key to exit>"); Console.ReadKey(); } }
//public int pid; //public string hookExe, hookDLL; /* * public Hooking(int pid, string hookExe, string hookDLL) * { * this.hookExe = hookExe; * this.hookDLL = hookDLL; * this.pid = pid; * } */ public static void hook(int pid, string descriptor, string hookExe, string hookDLL32, string hookDLL64, params object[] parameters) { try { Config.Register(descriptor, hookDLL32, hookExe); if (!hookDLL32.ToLower().Equals(hookDLL64.ToLower())) { Config.Register(descriptor, hookDLL32, hookExe); } Console.WriteLine("Registered!"); /* * EasyHook.RemoteHooking.IpcCreateServer<injectorInterface.GetType()>(ref * ChannelName, WellKnownObjectMode.SingleCall); */ EasyHook.RemoteHooking.Inject(pid, hookDLL32, hookDLL64, parameters); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
#pragma warning disable 0028 public static int Main(String InParam) { HelperServiceInterface Interface; Assembly UserAssembly = null; Type EntryPoint = null; ManagedRemoteInfo RemoteInfo; REMOTE_ENTRY_INFO UnmanagedInfo = new REMOTE_ENTRY_INFO(); if (InParam == null) { return(0); } /* * We will now connect to our hooking host. This is to provide extensive * error information. */ try { Marshal.PtrToStructure( (IntPtr)Int64.Parse(InParam, System.Globalization.NumberStyles.HexNumber), UnmanagedInfo); Byte[] PassThruBytes = new Byte[UnmanagedInfo.UserDataSize]; MemoryStream PassThruStream = new MemoryStream(); BinaryFormatter Format = new BinaryFormatter(); // Workaround for deserialization when not using GAC registration Format.Binder = new AllowAllAssemblyVersionsDeserializationBinder(); Marshal.Copy(UnmanagedInfo.UserData, PassThruBytes, 0, UnmanagedInfo.UserDataSize); PassThruStream.Write(PassThruBytes, 0, PassThruBytes.Length); PassThruStream.Position = 0; RemoteInfo = (ManagedRemoteInfo)Format.Deserialize(PassThruStream); Interface = RemoteHooking.IpcConnectClient <HelperServiceInterface>(RemoteInfo.ChannelName); // ensure connection... Interface.Ping(); if (!ConnectedChannels.Contains(RemoteInfo.ChannelName)) { ConnectedChannels.Add(RemoteInfo.ChannelName); return(1); } } catch (Exception ExtInfo) { Config.PrintError(ExtInfo.ToString()); return(0); } try { // adjust host PID in case of WOW64 bypass and service help... UnmanagedInfo.m_HostPID = RemoteInfo.HostPID; // prepare parameter array Object[] ParamArray = new Object[1 + RemoteInfo.UserParams.Length]; ParamArray[0] = (RemoteHooking.IContext)UnmanagedInfo; for (int i = 0; i < RemoteInfo.UserParams.Length; i++) { ParamArray[i + 1] = RemoteInfo.UserParams[i]; } /* * After this we are ready to load the user supplied library. */ Object Instance = null; try { // First attempt to load the library using its full name (e.g. strong name) if (!String.IsNullOrEmpty(RemoteInfo.UserLibraryName)) { try { UserAssembly = Assembly.Load(RemoteInfo.UserLibraryName); Config.PrintComment("SUCCESS: Assembly.Load({0})", RemoteInfo.UserLibraryName); } catch (Exception e) { Config.PrintWarning("FAIL: Assembly.Load({0}) - {1}", RemoteInfo.UserLibraryName, e.ToString()); } } // If loading by strong name failed, attempt to load the assembly from its file location if (UserAssembly == null) { try { UserAssembly = Assembly.LoadFrom(RemoteInfo.UserLibrary); Config.PrintComment("SUCCESS: Assembly.LoadFrom({0})", RemoteInfo.UserLibrary); } catch (Exception e) { Config.PrintWarning("FAIL: Assembly.LoadFrom({0}) - {1}", RemoteInfo.UserLibrary, e.ToString()); } } if (UserAssembly == null) { Config.PrintError("Could not load assembly {0}, {1}", RemoteInfo.UserLibrary, RemoteInfo.UserLibraryName); return(0); } // Only attempt to deserialise parameters after we have loaded the UserAssembly // this allows types from the UserAssembly to be passed as parameters BinaryFormatter format = new BinaryFormatter(); format.Binder = new AllowAllAssemblyVersionsDeserializationBinder(UserAssembly); for (int i = 1; i < ParamArray.Length; i++) { using (MemoryStream ms = new MemoryStream((byte[])ParamArray[i])) { ParamArray[i] = format.Deserialize(ms); } } // search for user library entry point... Type[] ExportedTypes = UserAssembly.GetExportedTypes(); for (int iType = 0; iType < ExportedTypes.Length; iType++) { EntryPoint = ExportedTypes[iType]; if (EntryPoint.GetInterface("EasyHook.IEntryPoint") != null) { break; } EntryPoint = null; } if (EntryPoint == null) { throw new EntryPointNotFoundException("The given user library does not export a proper type implementing the 'EasyHook.IEntryPoint' interface."); } // test for strictly typed Run() method MethodInfo Run = EntryPoint.GetMethod("Run", BindingFlags.Public | BindingFlags.Instance); if (Run != null) { if (ParamArray.Length != Run.GetParameters().Length) { throw new MissingMethodException("The given user library does export a Run() method in the 'EasyHook.IEntryPoint' interface, but the parameter count does not match!"); } for (int i = 0; i < ParamArray.Length; i++) { var param = Run.GetParameters()[i]; if (param.ParameterType.IsByRef && ParamArray[i] == null) // allow null parameter values { continue; } if (!param.ParameterType.IsInstanceOfType(ParamArray[i])) { Config.PrintError("Run() parameter {0} type {1}, does not match input parameter type {2}", i, param.ParameterType.AssemblyQualifiedName, ParamArray[i].GetType().AssemblyQualifiedName); throw new MissingMethodException( "The given user library does export a Run() method in the 'EasyHook.IEntryPoint' interface, but the parameter types do not match!"); } } } else { throw new MissingMethodException("The given user library does not export a proper Run() method in the 'EasyHook.IEntryPoint' interface."); } // assemble user parameters and initialize library... Instance = EntryPoint.InvokeMember(null, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, ParamArray); // notify the host about successful injection... Interface.InjectionCompleted(RemoteHooking.GetCurrentProcessId()); } catch (Exception ExtInfo) { // we will now get extensive error information on host side... try { Interface.InjectionException(RemoteHooking.GetCurrentProcessId(), ExtInfo); } finally { Instance = null; Release(EntryPoint); } return(-1); } try { /* * After this it is safe to enter the main method, which will block until assembly unloading... * From now on the user library has to take care about error reporting! */ EntryPoint.InvokeMember("Run", BindingFlags.Public | BindingFlags.Instance | BindingFlags.ExactBinding | BindingFlags.InvokeMethod, null, Instance, ParamArray); } finally { Instance = null; Release(EntryPoint); } } catch (Exception ExtInfo) { Config.PrintWarning(ExtInfo.ToString()); return(-1); } finally { if (ConnectedChannels.Contains(RemoteInfo.ChannelName)) { ConnectedChannels.Remove(RemoteInfo.ChannelName); } } return(0); }
static void Main(string[] args) { bool show_help = false; var options = new OptionSet() { { "i|ui", "Enable UI", v => Globals.UI = v != null }, { "c|characters", "Write characters", v => Globals.writeChars = v != null }, { "m|memory", "Read info from memory(use this if normal reading fails on zoning) - this might not work on your current ffxiv version", v => Globals.memory = v != null }, { "d|db", "Connect to a database", v => Globals.DB = v != null }, { "x|xml", "Write to mobdef XMLs", v => Globals.xmlOutput = v != null }, { "t|table", "Write to CSV table", v => Globals.csvOutput = v != null }, { "h|help", "Show this message and exit", v => show_help = v != null }, { "dbhost=", "MySQL server to write actors into, default: localhost", v => Globals.dbhost = v }, { "dbuser="******"MySQL username, default: root", v => Globals.dbuser = v }, { "dbpwd=", "MySQL password, default: empty", v => Globals.dbpwd = v }, { "dbname=", "MySQL database name, default: sapphire", v => Globals.dbname = v }, { "ooverride=", "Overrides the output directory/filename, default: date and time of launch", v => Globals.outputOverride = v }, }; List <string> extra; try { extra = options.Parse(args); } catch (OptionException e) { Console.WriteLine(e.Message); Console.WriteLine("Try `--help' for more information."); return; } if (show_help) { Console.WriteLine("Usage: [OPTIONS]+"); Console.WriteLine("\nOptions:"); options.WriteOptionDescriptions(Console.Out); return; } Globals.exdreader = new ExdCsvReader(); if (Globals.UI) { Console.WriteLine("Main: Opening UI"); Thread t = new Thread(new ThreadStart(StartNewStaThread)); t.Start(); } if (!System.IO.File.Exists("hook.dll")) { Console.WriteLine("Main: Could not find DLL!"); Environment.Exit(0); } Console.WriteLine("Main: Looking for ffxiv pid..."); try { RemoteHooking.IpcCreateServer <RemoteMon>(ref channelName, System.Runtime.Remoting.WellKnownObjectMode.Singleton); int pid = -1; foreach (Process p in Process.GetProcessesByName("ffxiv")) { pid = p.Id; } if (pid == -1) { foreach (Process p in Process.GetProcessesByName("ffxiv_dx11")) { pid = p.Id; } } if (pid == -1) { Console.WriteLine("Main: Could not find pid for ffxiv!"); Console.ReadLine(); return; } Globals.ffxivPid = pid; Console.WriteLine("Main: PID: {0}, injecting", pid); RemoteHooking.Inject(pid, InjectionOptions.DoNotRequireStrongName, "hook.dll", "hook.dll", new String[] { channelName }); } catch (Exception ExtInfo) { Console.WriteLine("Main: There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); Console.ReadLine(); } while (true) { Thread.Sleep(1000); } }
private void runExperiment(ProgramStartList descr_list) { string report_directory = createReportDirectory(); StreamWriter malicious_list_sw = new StreamWriter(new FileStream(MALICOUS_LIST_FILE_PATH, FileMode.Append)); try { foreach (ProgramStartDescription program_start_decr in descr_list) { try { Process process = message_server.startProcessAndInject(program_start_decr); string report_file_path = report_directory + generateFileName(process); StreamWriter sw = new StreamWriter(new FileStream(report_file_path, FileMode.CreateNew)); try { Console.WriteLine("Waiting for process to end..."); bool result = message_server.waitForProcessToEnd(process, program_start_decr.max_running_time); Console.WriteLine("Writting report to file: " + report_file_path); #region Write a report to file message_server.waitForTheEndOfProcessing(); sw.WriteLine(program_start_decr); Place.writeStatistics(Place.PrintLevel.Medium, sw); //Check if executable exposed any detectable malicious functionality // and write path to it into report file. IEnumerable <Place> detection_places = Place.getDetectionPlaces(); foreach (Place place in detection_places) { if (!place.isVirgin()) { Console.WriteLine("We have detected something for the program launched"); malicious_list_sw.WriteLine(program_start_decr.image_path); break; } } malicious_list_sw.Flush(); sw.WriteLine(result ? "Exited" : "Killed"); sw.Flush(); } catch (Exception e) { Console.WriteLine("APIMonMain.runExperiment Error while processing"); Console.WriteLine(e); } finally { sw.Close(); } #endregion //cleaning up Place.clearAllPlaces(); System.GC.Collect(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while running target: " + program_start_decr.image_path + "\r\n{0}", ExtInfo.ToString()); //throw ExtInfo; } } } finally { malicious_list_sw.Close(); } }
public void Inject() { try { RemoteHooking.Inject( TargetPID, "FileOpenMonitor.dll", "FileOpenMonitor.dll", ChannelName); } catch (Exception ExtInfo) { System.Diagnostics.Debug.WriteLine("There was an error while connecting to target {1}:\r\n{0}", ExtInfo.ToString(), TargetPID); } }
public static void hook(int pid, string descriptor, string hookExe, string hookDLL32, string hookDLL64, params object[] parameters) { try { Config.Register(descriptor, hookDLL32, hookExe); if (!hookDLL32.ToLower().Equals(hookDLL64.ToLower())) { Config.Register(descriptor, hookDLL32, hookExe); } Console.WriteLine("Registered!"); EasyHook.RemoteHooking.Inject(pid, hookDLL32, hookDLL64, parameters); 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) { 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(); }
static void Main(string[] args) { Int32 TargetPID = 0; if ((args.Length != 1) || !Int32.TryParse(args[0], out TargetPID)) { Console.WriteLine(); Console.WriteLine("Usage: MSAccessHookTests %PID%"); Console.WriteLine(); return; } try { string _ChannelName = null; RemoteHooking.IpcCreateServer <FileMonInterface>(ref _ChannelName, WellKnownObjectMode.SingleCall); ChannelName = _ChannelName; RemoteHooking.Inject( TargetPID, InjectionOptions.NoService, "MSAccessHookTests.exe", "MSAccessHookTests.exe", ChannelName); Console.ReadLine(); } catch (Exception ExtInfo) { Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString()); } }
#pragma warning disable 0028 public static int Main(String InParam) { HelperServiceInterface Interface; Assembly UserAssembly = null; Type EntryPoint = null; ManagedRemoteInfo RemoteInfo; REMOTE_ENTRY_INFO UnmanagedInfo = new REMOTE_ENTRY_INFO(); if (InParam == null) { return(0); } /* * We will now connect to our hooking host. This is to provide extensive * error information. */ try { Marshal.PtrToStructure( (IntPtr)Int64.Parse(InParam, System.Globalization.NumberStyles.HexNumber), UnmanagedInfo); Byte[] PassThruBytes = new Byte[UnmanagedInfo.UserDataSize]; MemoryStream PassThruStream = new MemoryStream(); BinaryFormatter Format = new BinaryFormatter(); Marshal.Copy(UnmanagedInfo.UserData, PassThruBytes, 0, UnmanagedInfo.UserDataSize); PassThruStream.Write(PassThruBytes, 0, PassThruBytes.Length); PassThruStream.Position = 0; RemoteInfo = (ManagedRemoteInfo)Format.Deserialize(PassThruStream); Interface = RemoteHooking.IpcConnectClient <HelperServiceInterface>(RemoteInfo.ChannelName); // ensure connection... Interface.Ping(); if (!ConnectedChannels.Contains(RemoteInfo.ChannelName)) { ConnectedChannels.Add(RemoteInfo.ChannelName); return(1); } } catch (Exception ExtInfo) { Config.PrintError(ExtInfo.ToString()); return(0); } try { // adjust host PID in case of WOW64 bypass and service help... UnmanagedInfo.m_HostPID = RemoteInfo.HostPID; // prepare parameter array Object[] ParamArray = new Object[1 + RemoteInfo.UserParams.Length]; ParamArray[0] = (RemoteHooking.IContext)UnmanagedInfo; for (int i = 0; i < RemoteInfo.UserParams.Length; i++) { ParamArray[i + 1] = RemoteInfo.UserParams[i]; } /* * After this we are ready to load the user supplied library. */ Object Instance = null; try { UserAssembly = Assembly.LoadWithPartialName(RemoteInfo.UserLibrary); // search for user library entry point... Type[] ExportedTypes = UserAssembly.GetExportedTypes(); for (int iType = 0; iType < ExportedTypes.Length; iType++) { EntryPoint = ExportedTypes[iType]; if (EntryPoint.GetInterface("EasyHook.IEntryPoint") != null) { break; } EntryPoint = null; } if (EntryPoint == null) { throw new EntryPointNotFoundException("The given user library does not export a proper type implementing the 'EasyHook.IEntryPoint' interface."); } // test for strictly typed Run() method MethodInfo Run = EntryPoint.GetMethod("Run", BindingFlags.Public | BindingFlags.Instance); if (Run != null) { if (ParamArray.Length != Run.GetParameters().Length) { throw new MissingMethodException("The given user library does export a Run() method in the 'EasyHook.IEntryPoint' interface, but the parameter count does not match!"); } for (int i = 0; i < ParamArray.Length; i++) { if (!Run.GetParameters()[i].ParameterType.IsInstanceOfType(ParamArray[i])) { throw new MissingMethodException("The given user library does export a Run() method in the 'EasyHook.IEntryPoint' interface, but the parameter types do not match!"); } } } else { throw new MissingMethodException("The given user library does not export a proper Run() method in the 'EasyHook.IEntryPoint' interface."); } // assemble user parameters and initialize library... Instance = EntryPoint.InvokeMember(null, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, ParamArray); // notify the host about successful injection... Interface.InjectionCompleted(RemoteHooking.GetCurrentProcessId()); } catch (Exception ExtInfo) { // we will now get extensive error information on host side... try { Interface.InjectionException(RemoteHooking.GetCurrentProcessId(), ExtInfo); } finally { Instance = null; Release(EntryPoint); } return(-1); } try { /* * After this it is safe to enter the main method, which will block until assembly unloading... * From now on the user library has to take care about error reporting! */ EntryPoint.InvokeMember("Run", BindingFlags.Public | BindingFlags.Instance | BindingFlags.ExactBinding | BindingFlags.InvokeMethod, null, Instance, ParamArray); } finally { Instance = null; Release(EntryPoint); } } catch (Exception ExtInfo) { Config.PrintWarning(ExtInfo.ToString()); return(-1); } finally { if (ConnectedChannels.Contains(RemoteInfo.ChannelName)) { ConnectedChannels.Remove(RemoteInfo.ChannelName); } } return(0); }
public static int Main(String InParam) { HelperServiceInterface Interface; String[] Params; String HostChannel; Assembly UserAssembly = null; Type EntryPoint = null; if (InParam == null) { return(-1); } /* * We will now connect to our hooking host. This is to provide extensive * error information. */ try { Params = InParam.Split('|'); if (Params.Length != 4) { return(-1); } HostChannel = Params[0]; Interface = RemoteHooking.IpcConnectClient <HelperServiceInterface>(HostChannel); // ensure connection... Interface.Ping(); if (!ConnectedChannels.Contains(HostChannel)) { ConnectedChannels.Add(HostChannel); return(0); } } catch (Exception ExtInfo) { Config.PrintError(ExtInfo.ToString()); return(-2); } try { /* * After this we are ready to load the user supplied library. */ String UserLibrary = Params[1]; String InfoPtr = Params[3]; List <Object> UserParams = new List <object>(); Object Instance = null; RemoteHooking.SetWakeUpThreadID(Int32.Parse(Params[2])); try { UserAssembly = Assembly.LoadWithPartialName(UserLibrary); // search for user library entry point... Type[] ExportedTypes = UserAssembly.GetExportedTypes(); for (int iType = 0; iType < ExportedTypes.Length; iType++) { EntryPoint = ExportedTypes[iType]; if (EntryPoint.GetInterface("EasyHook.IEntryPoint") != null) { break; } EntryPoint = null; } if (EntryPoint == null) { throw new EntryPointNotFoundException("The given user library does not export a proper type implementing the 'IEasyHookInjection' interface."); } // parse injection information (should work always as there is nothing tricky about it)... RemoteHooking.IContext Context = RemoteHooking.QueryContext(InfoPtr); // assemble user parameters and initialize library... BinaryFormatter Format = new BinaryFormatter(); UserParams.Add(Context); try { UserParams.AddRange((Object[])Format.Deserialize(new MemoryStream(Context.UserData))); } catch (Exception ExtInfo) { throw new ArgumentException("Unable to deserialize user supplied argument list.", ExtInfo); } Instance = EntryPoint.InvokeMember(null, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, UserParams.ToArray()); // notify the host about successful injection... Interface.InjectionCompleted(RemoteHooking.GetCurrentProcessId()); } catch (Exception ExtInfo) { // we will now get extensive error information on host side... try { Interface.InjectionException(RemoteHooking.GetCurrentProcessId(), ExtInfo); } finally { Instance = null; Release(EntryPoint); } return(-1); } try { /* * After this it is safe to enter the main method, which will block until assembly unloading... * From now on the user library has to take care about error reporting! */ EntryPoint.InvokeMember("Run", BindingFlags.Public | BindingFlags.Instance | BindingFlags.ExactBinding | BindingFlags.InvokeMethod, null, Instance, UserParams.ToArray()); } finally { Instance = null; Release(EntryPoint); } } catch (Exception ExtInfo) { Config.PrintWarning(ExtInfo.ToString()); return(-1); } finally { if (ConnectedChannels.Contains(HostChannel)) { ConnectedChannels.Remove(HostChannel); } } return(0); }
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()); } }