public override void InstallHook() { CreateProcessHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "CreateProcessW"), new DCreateProcessW(CreateProcessW_Hooked), this.Injector); CreateProcessHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); ExitProcessHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "ExitProcess"), new DExitProcess(ExitProcess_Hooked), this.Injector); ExitProcessHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); TerminateProcessHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "TerminateProcess"), new DTerminateProcess(TerminateProcess_Hooked), this.Injector); TerminateProcessHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); CreateThreadHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "CreateThread"), new DCreateThread(CreateThread_Hooked), this.Injector); CreateThreadHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); TerminateThreadHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "TerminateThread"), new DTerminateThread(TerminateThread_Hooked), this.Injector); TerminateThreadHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); }
/// <summary> /// Installs an unmanaged hook. After this you'll have to activate it by setting a proper <see cref="ThreadACL" />. /// <see cref="HookRuntimeInfo" /> WON'T be supported! Refer to the native "LhBarrierXxx" APIs to /// access unmanaged hook runtime information. /// </summary> /// <remarks> /// <para> /// Note that not all entry points are hookable! In general methods like <c>CreateFileW</c> /// won't cause any trouble. But there may be methods that are not hookable because their /// entry point machine code is not eligable to be hooked. You should test all hooks on /// common environments like "Windows XP x86/x64 SP1/SP2/SP3" and "Windows Vista x86/x64 (SP1)". /// This is the only way to ensure that your application will work well on most machines. /// </para> /// <para> /// Unmanaged hooks will require a native DLL which handles the requests. This way /// you will get a high-performance interface, because /// a switch from unmanaged to managed code seems to be rather time consuming without doing anything /// useful (at least nothing visible); so a hook omitting this switch will be handled one or two /// orders of magnitudes faster until finally your handler gains execution. But as a managed hook is still executed /// within at last 1000 nano-seconds, even the "slow" managed implementation will be fast enough in most /// cases. With C++.NET you would be able to provide such native high-speed hooks for frequently /// called API methods, while still using managed ones for usual API methods, within a single assembly! /// A pure unmanaged, empty hook executes in approx. 70 nano-seconds, which is incredible fast /// considering the thread deadlock barrier and thread ACL negotiation that are already included in this benchmark! /// </para> /// </remarks> /// <param name="InTargetProc">A target entry point that should be hooked.</param> /// <param name="InNewProc"> /// A handler with the same signature as the original entry point /// that will be invoked for every call that has passed the Thread Deadlock Barrier and various integrity checks. /// </param> /// <param name="InCallback">An uninterpreted callback that will later be available through <c>LhBarrierGetCallback()</c>.</param> /// <returns> /// A handle to the newly created hook. /// </returns> /// <exception cref="OutOfMemoryException"> /// Not enough memory available to complete the operation. On 64-Bit this may also indicate /// that no memory can be allocated within a 31-Bit boundary around the given entry point. /// </exception> /// <exception cref="ArgumentException"> /// The given function pointer does not map to executable memory (valid machine code) or /// you passed <c>null</c> as delegate. /// </exception> /// <exception cref="NotSupportedException"> /// The given entry point contains machine code that can not be hooked. /// </exception> /// <exception cref="InsufficientMemoryException"> /// The maximum amount of hooks has been installed. This is currently set to MAX_HOOK_COUNT (1024). /// </exception> public static LocalHook CreateUnmanaged( IntPtr InTargetProc, IntPtr InNewProc, IntPtr InCallback) { var Result = new LocalHook(); Result.m_Callback = InCallback; Result.m_Handle = Marshal.AllocCoTaskMem(IntPtr.Size); Result.m_SelfHandle = GCHandle.Alloc(Result, GCHandleType.Weak); try { NativeAPI.LhInstallHook( InTargetProc, InNewProc, InCallback, Result.m_Handle); } catch (Exception e) { Marshal.FreeCoTaskMem(Result.m_Handle); Result.m_Handle = IntPtr.Zero; Result.m_SelfHandle.Free(); throw e; } Result.m_ThreadACL = new HookAccessControl(Result.m_Handle); return(Result); }
public override void InstallHook() { sendHook = LocalHook.Create( LocalHook.GetProcAddress("Ws2_32.dll", "send"), new Dsend(send_Hooked), this.Injector); sendHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); sendtoHook = LocalHook.Create( LocalHook.GetProcAddress("Ws2_32.dll", "sendto"), new Dsendto(sendto_Hooked), this.Injector); sendtoHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); recvHook = LocalHook.Create( LocalHook.GetProcAddress("Ws2_32.dll", "recv"), new Drecv(recv_Hooked), this.Injector); recvHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); recvFunc = LocalHook.GetProcDelegate<Drecv>("Ws2_32.dll", "recv"); recvfromHook = LocalHook.Create( LocalHook.GetProcAddress("Ws2_32.dll", "recvfrom"), new Drecvfrom(recvfrom_Hooked), this.Injector); recvfromHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); recvfromFunc = LocalHook.GetProcDelegate<Drecvfrom>("Ws2_32.dll", "recvfrom"); }
public void Run(RemoteHooking.IContext InContext, String InChannelName) { // install hook... try { CreateFileHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new DCreateFile(CreateFile_Hooked), this); CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); RemoteHooking.WakeUpProcess(); } catch (Exception ExtInfo) { Interface.ReportException(ExtInfo); return; } //Interface.IsInstalled(RemoteHooking.GetCurrentProcessId()); try { while (true) { Interface.Ping(); } } catch { // } }
public void Run( RemoteHooking.IContext InContext, String InChannelName) { // install hook... try { LocalHook.BeginUpdate(true); CreateFileHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new DCreateFile(CreateFile_Hooked), this); LocalHook.EndUpdate(); CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); } catch (Exception ExtInfo) { Interface.ReportException(ExtInfo); return; } Interface.IsInstalled(RemoteHooking.GetCurrentProcessId()); RemoteHooking.WakeUpProcess(); // wait for host process termination... try { while (true) { Thread.Sleep(500); // transmit newly monitored file accesses... if (Queue.Count > 0) { String[] Package = null; lock (Queue) { Package = Queue.ToArray(); Queue.Clear(); } Interface.OnCreateFile(RemoteHooking.GetCurrentProcessId(), Package); } else Interface.Ping(); } } catch { // Ping() will raise an exception if host is unreachable } }
public DX9Controller(HWSettings settings) { this._settings = settings; this.Name = typeof(DX9Controller).Name; IntPtr direct3D = Direct3DCreate9(32); try { if (direct3D == IntPtr.Zero){ MessageBox.Show("error"); throw new Exception("Failed to create D3D."); } IntPtr adapterIdentPtr = Marshal.ReadIntPtr(Marshal.ReadIntPtr(direct3D), 20); GetAdapterIdentifierOriginal = (GetAdapterIdentifierDelegate)Marshal.GetDelegateForFunctionPointer(adapterIdentPtr, typeof(GetAdapterIdentifierDelegate)); _name = string.Format("GetAdapterIdentHook_{0:X}", adapterIdentPtr.ToInt32()); _hook = LocalHook.Create(adapterIdentPtr, new GetAdapterIdentifierDelegate(GetAdapterIdentifierDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); } catch (Exception ex) { HookManager.Log("[DX9Controller] Exception: " + ex.ToString()); this.Error = true; } }
public override void Initialize() { Form form = new Form(); IntPtr intPtr = Direct3DCreate9(32u); if (intPtr == IntPtr.Zero) { throw new Exception("Failed to create D3D."); } D3D9.Struct0 @struct = new D3D9.Struct0 { bool_0 = true, uint_6 = 1u, uint_2 = 0u }; D3D9.Delegate4 @delegate = (D3D9.Delegate4)Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(intPtr), 64), typeof(D3D9.Delegate4)); IntPtr intPtr2; if (@delegate(intPtr, 0u, 1u, form.Handle, 32u, ref @struct, out intPtr2) < 0) { throw new Exception("Failed to create device."); } this.EndScenePointer = Marshal.ReadIntPtr(Marshal.ReadIntPtr(intPtr2), 168); D3D9.Delegate3 delegate2 = (D3D9.Delegate3)Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(intPtr2), 8), typeof(D3D9.Delegate3)); D3D9.Delegate3 delegate3 = (D3D9.Delegate3)Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(intPtr), 8), typeof(D3D9.Delegate3)); delegate2(intPtr2); delegate3(intPtr); form.Dispose(); this.delegate2_0 = (D3D9.Delegate2)Marshal.GetDelegateForFunctionPointer(this.EndScenePointer, typeof(D3D9.Delegate2)); this.localHook_0 = LocalHook.Create(this.EndScenePointer, new D3D9.Delegate2(this.method_0), this); int[] exclusiveACL = new int[1]; localHook_0.ThreadACL.SetExclusiveACL(exclusiveACL); }
public void Run( RemoteHooking.IContext InContext, String InArg1) { try { LocalHook.BeginUpdate(false); { CreateFileHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new DCreateFile(CreateFile_Hooked), this); } LocalHook.EndUpdate(); /* * Don't forget that all hooks will start deaktivated... * The following ensures that all threads are intercepted: */ CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[1]); } catch (Exception e) { /* Now we should notice our host process about this error... */ Interface.ReportError(RemoteHooking.GetCurrentProcessId(), e); return; } // wait for host process termination... try { while (Interface.Ping(RemoteHooking.GetCurrentProcessId())) { Thread.Sleep(500); // transmit newly monitored file accesses... if (Queue.Count > 0) { String[] Package = null; lock (Queue) { Package = Queue.ToArray(); Queue.Clear(); } Interface.OnCreateFile(RemoteHooking.GetCurrentProcessId(), Package); } } } catch { // NET Remoting will raise an exception if host is unreachable } }
public RegistryHook(IntPtr address, string prodKey) { _prodKey = prodKey; _name = string.Format("RegQueryValueExAHook_{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new RegQueryValueExADelegate(RegQueryValueExADetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] {0}); }
public AppdataHook(IntPtr address, string userLogin) { _userLogin = userLogin; _name = string.Format("AppDataHook_{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new SHGetFolderPathDelegate(SHGetFolderPathDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] {0}); }
public void Dispose() { if (_hook == null) return; _hook.Dispose(); _hook = null; }
public MemoryHook(IntPtr address, ulong totalPhys) { _totalPhys = totalPhys; _name = string.Format("MemoryHook{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new GlobalMemoryStatusDelegate(GlobalMemoryStatusDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] {0}); }
/// <summary> /// Calls <see cref="LocalHook.Release"/> if an entrypoint has been initialized. /// </summary> /// <param name="entryPoint"></param> private static void Release(Type entryPoint) { if (entryPoint == null) { return; } LocalHook.Release(); }
public void Run( RemoteHooking.IContext InContext, String InChannelName) { // install hook... try { CreateKeywordHook = LocalHook.Create( LocalHook.GetProcAddress("python27.dll", "PyEval_CallObjectWithKeywords"), new DCallKeywords(CallKeywords_Hooked), this); CreateKeywordHook.ThreadACL.SetExclusiveACL(new Int32[] {0}); CreateGetModuleHandleAHook = LocalHook.Create(LocalHook.GetProcAddress("kernel32", "GetModuleHandleA"), new DGetModuleHandleA(GetModuleHandleHooked), this); CreateGetModuleHandleAHook.ThreadACL.SetExclusiveACL(new Int32[] {0}); } catch (Exception ExtInfo) { Interface.ReportException(ExtInfo); return; } Interface.IsInstalled(RemoteHooking.GetCurrentProcessId()); RemoteHooking.WakeUpProcess(); // wait for host process termination... try { while (true) { Thread.Sleep(500); // transmit newly monitored file accesses... if (Queue.Count > 0) { String[] Package = null; lock (Queue) { Package = Queue.ToArray(); Queue.Clear(); } } else Interface.Ping(); } } catch { // Ping() will raise an exception if host is unreachable } }
public NetworkAdapterHook(IntPtr address, string guid, string mac, string ipaddress) { _guid = guid; _mac = mac; _address = ipaddress; _name = string.Format("GetAdaptersInfoHook_{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new GetAdaptersInfoDelegate(GetAdaptersInfoDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] {0}); }
public override void Hook() { SwapBuffers_Hook = LocalHook.Create (LocalHook.GetProcAddress ("gdi32.dll","SwapBuffers"), new Delegate_SwapBuffers(SwapBuffers_Hooked),this); //gfx = Graphics.FromImage(imag); //gfx.FillRectangle(Brushes.Blue, 0, 0, 350, 350); SwapBuffers_Hook.ThreadACL.SetExclusiveACL(new Int32[1]); this.DebugMessage("Hook: Done" + DateTime.Now.ToString() + ":" + DateTime.Now.Millisecond.ToString()); }
public GraphicsCardHook(IntPtr address, Settings settings) { _settings = settings; var dxgiHandle = Utility.GetModuleHandle("dxgi.dll"); var getDescPtr = dxgiHandle + getDescOffset; GetDesc1Original = (GetDesc1Delegate) Marshal.GetDelegateForFunctionPointer(getDescPtr, typeof (GetDesc1Delegate)); _name = string.Format("GetDescHook_{0:X}", getDescPtr.ToInt32()); _hook = LocalHook.Create(getDescPtr, new GetDesc1Delegate(GetDesc1Detour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] {0}); }
public CryptHashDataController(IntPtr address) { this.Name = typeof(CryptHashDataController).Name; try { _name = string.Format("CryptDataHash_{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new CryptHashDataDelegate(CryptHashDataDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); } catch (Exception) { this.Error= true; } }
public override void Hook() { this.DebugMessage("Hook: Begin"); // First we need to determine the function address for IDirect3DDevice9 Device device; List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>(); this.DebugMessage("Hook: Before device creation"); using (Direct3D d3d = new Direct3D()) { this.DebugMessage("Hook: Device created"); using (device = new Device(d3d, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 })) { id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(device.ComPointer, D3D9_DEVICE_METHOD_COUNT)); } } // We want to hook each method of the IDirect3DDevice9 interface that we are interested in // 42 - EndScene (we will retrieve the back buffer here) Direct3DDevice_EndSceneHook = LocalHook.Create( id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene], // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to: // (IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x1ce09), // A 64-bit app would use 0xff18 // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file new Direct3D9Device_EndSceneDelegate(EndSceneHook), this); // 16 - Reset (called on resolution change or windowed/fullscreen change - we will reset some things as well) Direct3DDevice_ResetHook = LocalHook.Create( id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset], // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to: //(IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x58dda), // A 64-bit app would use 0x3b3a0 // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file new Direct3D9Device_ResetDelegate(ResetHook), this); /* * Don't forget that all hooks will start deactivated... * The following ensures that all threads are intercepted: * Note: you must do this for each hook. */ Direct3DDevice_EndSceneHook.ThreadACL.SetExclusiveACL(new Int32[1]); Direct3DDevice_ResetHook.ThreadACL.SetExclusiveACL(new Int32[1]); this.DebugMessage("Hook: End"); }
public GlobalMemoryStatusController(IntPtr address, ulong totalPhys) { this._totalPhys = totalPhys; this.Name = typeof(GlobalMemoryStatusController).Name; try { _name = string.Format("MemoryHook{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new GlobalMemoryStatusDelegate(GlobalMemoryStatusDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); } catch (Exception) { this.Error = true; } }
public override void InstallHook() { RegCreateKeyHook = LocalHook.Create( LocalHook.GetProcAddress("Advapi32.dll", "RegCreateKeyW"), new DRegCreateKeyW(RegCreateKeyW_Hooked), this.Injector); RegCreateKeyHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); RegDeleteKeyHook = LocalHook.Create( LocalHook.GetProcAddress("Advapi32.dll", "RegDeleteKeyW"), new DRegDeleteKeyW(RegDeleteKeyW_Hooked), this.Injector); RegDeleteKeyHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); }
public InternetConnectAController() { Name = "InternetConnectAHook_" + "wininet.dll"; try { _hook = LocalHook.Create(LocalHook.GetProcAddress("wininet.dll", "InternetConnectA"), new HInternetConnectADelegate(HInternetConnectADetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); this.Error = false; } catch (Exception e) { this.Error = true; HookManager.Log("[" + Name + "] Exception: " + e); } }
public GetAdaptersInfoController(IntPtr address, string guid, string mac, string ipaddress) { this.Name = typeof(GetAdaptersInfoController).Name; _guid = guid; _mac = mac; _address = ipaddress; try { _name = string.Format("GetAdaptersInfoHook_{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new GetAdaptersInfoDelegate(GetAdaptersInfoDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); } catch (Exception) { this.Error = true; } }
public RegQueryValueExAController(IntPtr address, string prodKey) { _prodKey = prodKey; this.Name = typeof(RegQueryValueExAController).Name; try { _name = string.Format("RegQueryValueExAHook_{0:X}", address.ToInt32()); _hook = LocalHook.Create(address, new RegQueryValueExADelegate(RegQueryValueExADetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); } catch (Exception) { this.Error = true; } }
public void Run( RemoteHooking.IContext context, String channelName , TestComplexParameter parameter ) { try { CreateFileHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new DCreateFile(CreateFile_Hooked), this); /* * Don't forget that all hooks will start deactivated... * The following ensures that all threads are intercepted: */ CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[1]); } catch (Exception e) { /* Now we should notice our host process about this error... */ _interface.ReportException(e); return; } _interface.IsInstalled(RemoteHooking.GetCurrentProcessId()); _interface.SendMessage(parameter.Message); try { while (true) { Thread.Sleep(10); _interface.Ping(); } } catch { } }
public EnumProcessesController() { this.Error = false; this.Name = typeof(EnumProcessesController).Name; try { currentEvePID = Process.GetCurrentProcess().Id; this._hook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "K32EnumProcesses"), new Win32Hooks.EnumProcessesController.EnumProcessesDelegate(EnumProcessesDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); this.Error = false; } catch (Exception) { this.Error = true; } }
public void Load() { try { CreateFileHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new CreateFileDelegate(OnCreateFile), this); // All hooks start de-activated // The following ensures that this hook can be intercepted from all threads of this process CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[1]); } catch (Exception ex) { IpcInterface.PostException(ex); } }
public LoadLibraryWController() { this.Error = false; this.Name = typeof(LoadLibraryWController).Name; try { this._hook = LocalHook.Create( LocalHook.GetProcAddress("Kernel32.dll", "LoadLibraryW"), new Win32Hooks.LoadLibraryWController.LoadLibraryWDelegate(LoadLibraryWDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); this.Error = false; } catch (Exception) { this.Error = true; } }
public GetModuleHandleAController() { this.Error = false; this.Name = typeof(GetModuleHandleAController).Name; try { this._hook = LocalHook.Create( LocalHook.GetProcAddress("Kernel32.dll", "GetModuleHandleA"), new Win32Hooks.GetModuleHandleAController.GetModuleHandleADelegate(GetModuleHandleADetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); this.Error = false; } catch (Exception) { this.Error = true; } }
public IsDebuggerPresentController() { this.Error = false; this.Name = typeof(IsDebuggerPresentController).Name; try { this._hook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "IsDebuggerPresent"), new Win32Hooks.IsDebuggerPresentController.IsDebuggerPresentDelegate(IsDebuggerPresentDetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); this.Error = false; } catch (Exception) { this.Error = true; } }
public SHGetFolderPathAController(string newPathPersonal, string newPathLocalAppData) { NewPathPersonal = newPathPersonal; NewPathLocalAppData = newPathLocalAppData; this.Error = false; this.Name = typeof(SHGetFolderPathAController).Name; try { this._hook = LocalHook.Create( LocalHook.GetProcAddress("shell32.dll", "SHGetFolderPathA"), new Win32Hooks.SHGetFolderPathAController.SHGetFolderPathADelegate(SHGetFolderPathADetour), this); _hook.ThreadACL.SetExclusiveACL(new Int32[] { 1 }); this.Error = false; } catch (Exception) { this.Error = true; } }
private bool InstallHook() { bool installationSucceeded = true; try { m_writeConsoleHook = LocalHook.Create( LocalHook.GetProcAddress("kernel32.dll", "WriteFile"), new DWriteFile(WriteFile_Hooked), this ); m_writeConsoleHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); } catch (Exception e) { m_hookInterface.ReportException(e); installationSucceeded = false; } return installationSucceeded; }
/// <summary> /// Installs a managed hook. After this you'll have to activate it by setting a proper <see cref="ThreadACL"/>. /// </summary> /// <remarks> /// <para> /// Note that not all entry points are hookable! In general methods like <c>CreateFileW</c> /// won't cause any trouble. But there might be methods that are not hookable because their /// entry point machine code is not eligable to be hooked. You should test all hooks on /// common environments like "Windows XP x86/x64 SP2/SP3" and "Windows Vista x86/x64 (SP1)". /// This is the only way to ensure that your application will work well on most machines. /// </para><para> /// Your handler delegate has to use the <see cref="UnmanagedFunctionPointerAttribute"/> and /// shall map to the same native method signature, otherwise the application will crash! The best /// way is to use predefined delegates used in related P-Invoke implementations usually found with Google. /// If you know how to write such native delegates you won't need internet resources of course. /// I recommend using C++.NET which allows you to just copy the related windows API to your managed /// class and thread it as delegate without any changes. This will also speed up the whole thing /// because no unnecessary marshalling is required! C++.NET is also better in most cases because you /// may access the whole native windows API from managed code without any effort what significantly eases /// writing of hook handlers. /// </para> /// <para> /// The given delegate is automatically prevented from being garbage collected until the hook itself /// is collected... /// </para> /// </remarks> /// <param name="InTargetProc">A target entry point that should be hooked.</param> /// <param name="InNewProc">A handler with the same signature as the original entry point /// that will be invoked for every call that has passed the Fiber Deadlock Barrier and various integrity checks.</param> /// <returns> /// A handle to the newly created hook. /// </returns> /// <exception cref="OutOfMemoryException"> /// Not enough memory available to complete the operation. On 64-Bit this may also indicate /// that no memory can be allocated within a 31-Bit boundary around the given entry point. /// </exception> /// <exception cref="ArgumentException"> /// The given function pointer does not map to executable memory (valid machine code) or /// you passed <c>null</c> as delegate. /// </exception> /// <exception cref="NotSupportedException"> /// The given entry point contains machine code that can not be hooked. /// </exception> /// <exception cref="InsufficientMemoryException"> /// The maximum amount of hooks has been installed. This is currently set to MAX_HOOK_COUNT (1024). /// </exception> public static LocalHook Create( IntPtr InTargetProc, Delegate InNewProc, Object InCallback) { LocalHook Result = new LocalHook(); Result.m_Callback = InCallback; Result.m_HookProc = InNewProc; Result.m_Handle = Marshal.AllocCoTaskMem(IntPtr.Size); Result.m_SelfHandle = GCHandle.Alloc(Result, GCHandleType.Weak); Marshal.WriteIntPtr(Result.m_Handle, IntPtr.Zero); try { #if SUPPORT_THEME_HOOKS NativeAPI.LhInstallHook( InTargetProc, Marshal.GetFunctionPointerForDelegate(Result.m_HookProc), GCHandle.ToIntPtr(Result.m_SelfHandle), Result.m_Handle); #endif } catch (Exception) { Marshal.FreeCoTaskMem(Result.m_Handle); Result.m_Handle = IntPtr.Zero; Result.m_SelfHandle.Free(); throw; } Result.m_ThreadACL = new HookAccessControl(Result.m_Handle); return(Result); }