中文翻译-EasyHook - The reinvention of Windows API hooking.docx_第1页
中文翻译-EasyHook - The reinvention of Windows API hooking.docx_第2页
中文翻译-EasyHook - The reinvention of Windows API hooking.docx_第3页
中文翻译-EasyHook - The reinvention of Windows API hooking.docx_第4页
中文翻译-EasyHook - The reinvention of Windows API hooking.docx_第5页
已阅读5页,还剩20页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

/Doc?id=dc43n79n_139g4dsmzgr 1 Continuing Detours: the reinvention of Windows API Hooking1继续截获:重新改造Windows API 挂钩Microsoft Detours latest release was in December 2006. Now times have changed and the NET Framework has become more and more popular. Besides the well known unmanaged code hooking, EasyHook provides a way to hook unmanaged code from a managed environment. This implies several advantages:微软的Detours最新的版本是在2006年12月发布。而现在.Net框架越来越流行,除了大家知道的非托管理代码挂接,EasyHook提供一个从托管环境挂接非托管代码的方法。这意味着几个优点: No resource or memory leaks are left in the target 在目标中不会有资源和内存泄漏。 You can write pure managed hook handlers for unmanaged APIs 为非托管API写存托管的挂钩处理。 All hooks are installed and automatically removed in a stable manner 在稳定的意义上所有的挂构自动安装的移除。 You can use all the convenience managed code provides, like NET Remoting, WCF and WPF 你可以使用所有托管代码的便利,象Net Rmoting, WCF 和 WPF。 You will be able to write injection libraries and host processes compiled for AnyCPU, which will allow you to inject your code into 32- and 64-Bit processes from 64- and 32-Bit processes by using the very same assembly in all cases. 你可以为各种CPU写注入库和托管进程,你可以用相同的汇编将你的代码注入32和64位进程。This way hooking has become a simple task and you can now write hooking applications like FileMon or RegMon with a few lines of code.Further EasyHook 2.5 provides additional features like: Experimental stealth injection for unmanaged code not raising attention of any current AV 32- and 64-Bit Kernel mode hooking support, since Windows XP. A pure unmanaged hooking core which will improve performance, stability and compatibility. A solid unmanaged API for writing hooking apps and libraries without the NET Framework The unmanaged core does not require CRT bindings and thus will reduce deployment size about some megabytes. Also Windows 2000 SP4 and Windows Server 2008 SP1 can now be targeted with the same EasyHook binary. Minimal software requirements for end-users to execute applications using EasyHook: Windows 2000 SP4 or later Microsoft NET Framework 2.0 Redistributable Table of Content 1 Continuing Detours: the reinvention of Windows API Hooking 1.1 Security Advisor 1.2 A simple FileMon derivate 2 A deep look under the hook 2.1 Global Assembly Cache 2.2 Windows Defender 2.3 Injection A burden made easy o 2.3.1 Creating an already hooked process 2.4 The injected library entry point o 2.4.1 The library constructor o 2.4.2 The library Run-Method 2.5 Injection helper routines 2.6 How to install a hook 2.7 How to write a hook handler 2.8 Using Thread ACLs 2.9 Using handler utilities 2.10 The IPC helper API 2.11 Guidelines for stable hooking 2.12 A look into the future ATTENTIONThis Guide will cover the managed part of EasyHook only. Most things also apply to the unmanaged API. Refer to the “Unmanaged API Reference” for more information. The “Managed API Reference” also contains much additional information to the stuff covered here. LICENSE CHANGEEasyHook is now released under the Lesser GPL instead of the MIT License.ProcessMonitor ScreenshotThe following is a screenshot of my ProcessMonitor demo, shipping with the source code and the binary package: It allows you to intercept CreateFile calls of any process currently running in your system.1.1 Security Advisor Unlike what some (commercial) hooking libraries out there are advertising to boost sales, user-mode hooking can NEVER be an option to apply additional security checks in any safe manner. If you only want to “sandbox” a dedicated process, you know well about, and the process in fact doesnt know about EasyHook, this might succeed! But dont ever attempt to write any security software based on user mode hooking. It wont work, I promise you This is also why EasyHook does not support a so called “System wide” injection, which in fact is just an illusion, because as I said, with user-mode hooks this will always be impossible. But if you want to keep this illusion you may stick with other (commercial) libraries attempting to do soSince EasyHook 2.5, you are able to easily hook 32-Bit kernels. Even if EasyHook would allow hooking 64-Bit kernels, I dont recommend this because then you would get trouble with PatchGuard. Bypassing PatchGuard is possible, at least these days, but the chance of BSODing your customers PCs is too big. You should consider purchasing the PatchGuard API which will allow you to write security apps based on kernel mode interceptions. Kernel mode hooking (or the PatchGuard API) is the only option to apply additional security checks. Since Windows Vista, also the Windows Filtering Platform and other Vista specific APIs will be helpful to write security software!So what is user-mode hooking for? In general, user-mode hooking is intended for API monitoring, like Mark Russinovichs ProcessMonitor (alias FileMon/RegMon), resource leak detection, various malware which doesnt need to care about security issues, extending applications and libraries you dont have the source code for (also cracks may fall in this category), adding a compatibility layer for existing applications to run on newer OSes, etc. If anyone uses security in context of user-mode hooks, your alarm bells should ring!1.2 A simple FileMon derivate1.2一个简单的文件监视程序To prove that EasyHook really makes hooking simple, look at the following demo application, which will log all file accesses from a given process. We need a host process which injects the library and displays file accesses. It is possible to combine injection library and host process in one file as both are just threaded as valid NET assemblies, but I think to separate them is a more consistent approach. This demo will be used throughout the whole guide:为了证明EasyHook的确让挂接变得简单,看看下面的常规应用,它会将所有给定进程的文件获取全部记录下来.我们需要一个托管进程将库注入并显示文件访问信息.我们可能通过注入库和托管进程在一个文件中结合并作为有效的NET程序集,但我想还是把它们分开更协调一点,该演示会在整个指南中使用。using System;using System.Collections.Generic;using System.Runtime.Remoting;using System.Text;using System.Runtime.InteropServices;using EasyHook;namespace FileMon public class FileMonInterface : MarshalByRefObject public void IsInstalled(Int32 InClientPID) Console.WriteLine(文件访问监视器将被安装到目标 0 中.rn, InClientPID); public void OnCreateFile(Int32 InClientPID, String InFileNames) for (int i = 0; i InFileNames.Length; i+) Console.WriteLine(InFileNamesi); public void ReportException(Exception InInfo) Console.WriteLine(目标进程报告错误:rn + InInfo.ToString(); public void Ping() class Program static String ChannelName = null; static void Main(string args) try Config.Register(文件访问监视类演示程序, FileMon.exe, FileMonInject.dll); RemoteHooking.IpcCreateServer(ref ChannelName, WellKnownObjectMode.SingleCall); RemoteHooking.Inject( Int32.Parse(args0), FileMonInject.dll, FileMonInject.dll, ChannelName); Console.ReadLine(); catch (Exception ExtInfo) Console.WriteLine(当连接到目标时出现错误:rn0, ExtInfo.ToString(); The most complex part is the injected library which has to fulfill various requirements. We are hooking the CreateFile-API and redirecting all requests to our host process. The library will be unloaded if the host process is terminated:最复杂的部分是应用于各种需求的注入库。我们现在挂在CreateFile-API并重定向所有的请求到我们的托管进程。如果托管进程结束,库将卸载。using System;using System.Collections.Generic;using System.Text;using System.Threading;using System.Runtime.InteropServices;using EasyHook;namespace FileMonInject public class Main : EasyHook.IEntryPoint FileMon.FileMonInterface Interface; LocalHook CreateFileHook; Stack Queue = new Stack(); public Main(RemoteHooking.IContext InContext,String InChannelName) / 连接到托管. Interface = RemoteHooking.IpcConnectClient(InChannelName); public void Run(RemoteHooking.IContext InContext,String InChannelName) / 按装挂钩. try CreateFileHook = LocalHook.Create(LocalHook.GetProcAddress(kernel32.dll, CreateFileW), new DCreateFile(CreateFile_Hooked),this); CreateFileHook.ThreadACL.SetExclusiveACL(new Int32 0 ); catch (Exception ExtInfo) Interface.ReportException(ExtInfo); return; Interface.IsInstalled(RemoteHooking.GetCurrentProcessId(); / 等待托管进程结束. try while (true) Thread.Sleep(500); / 传送最新监视到的文件访问. if (Queue.Count 0) String Package = null; lock (Queue) Package = Queue.ToArray(); Queue.Clear(); Interface.OnCreateFile(RemoteHooking.GetCurrentProcessId(), Package); else Interface.Ping(); catch / NET Remoting在托管不可达时会触发异常 UnmanagedFunctionPointer(CallingConvention.StdCall,CharSet = CharSet.Unicode,SetLastError = true) delegate IntPtr DCreateFile(String InFileName,UInt32 InDesiredAccess,UInt32 InShareMode,IntPtr InSecurityAttributes,UInt32 InCreationDisposition,UInt32 InFlagsAndAttributes,IntPtr InTemplateFile); / 就使用P-Invoke执行获得从C#访问原始APIC# (这一步对 C+.NET来说没必要) DllImport(kernel32.dll,CharSet = CharSet.Unicode,SetLastError = true,CallingConvention = CallingConvention.StdCall) static extern IntPtr CreateFile(String InFileName,UInt32 InDesiredAccess,UInt32 InShareMode,IntPtr InSecurityAttributes,UInt32 InCreationDisposition,UInt32 InFlagsAndAttributes,IntPtr InTemplateFile); / 这里就是所有文件访问截取的地方! static IntPtr CreateFile_Hooked(String InFileName,UInt32 InDesiredAccess,UInt32 InShareMode,IntPtr InSecurityAttributes,UInt32 InCreationDisposition,UInt32 InFlagsAndAttributes,IntPtr InTemplateFile) try Main This = (Main)HookRuntimeInfo.Callback; lock (This.Queue) This.Queue.Push(InFileName); catch / 调用原始的API. return CreateFile(InFileName,InDesiredAccess,InShareMode,InSecurityAttributes,InCreationDisposition,InFlagsAndAttributes,InTemplateFile); Even if this might look strange, the next chapters will explain what is done there and why. You may start this application with a user defined target process ID as one and only parameter from command line. I recommend using the PID of “explorer.exe” because this will immediately produce output! Just browse your file system while running the FileMon utility:即使看上去挺奇怪,下一章将解释来龙去脉。你可以使用一自定义的进程ID启动该程序,只需要一个参数。我建议使用exploerer.exe进程,因为他很快就会有输出。只要在命令行上这样运行程序即可:Command line utility- FileMon.exe %PID% It is also possible to output the whole thing into a file what might provide more convenience:也可以这样输出放到一个文件中:Command line utility- FileMon.exe %PID% “C:MyLog.txt” 2 A deep look under the hook深入查看挂钩Now that you have seen the basic ideas of EasyHook and some sample code, we should start to discover what is really going on under the hood. In this chapter you will learn how to utilize most parts of the EasyHook API, injecting libraries into any process and hooking any API you want.现在你已经看到EasyHook的一些基本思想和一些示例代码,我们开始看看到底是怎么回事.这一章你会学到怎样用EasyHook API的主要部分,把库注入到任何进程和挂接任何你想要的API。2.1 Global Assembly Cache全局程序集缓存Currently EasyHook is expecting every injected assembly including all of its dependencies in the Global Assembly Cache (GAC). This is because the CLR will only search for assemblies in directories relative to the current application base directory and the GAC and therefore a target process normally has no access to EasyHook or your injected library. EasyHook is using a reference counter to make sure that multiple installations of the same assemblies from different applications can be managed. The following will register all EasyHook components and the two user assemblies required for injection in the GAC. The first parameter is just an uninterpreted string which should describe what your service is doing. All further parameters are expected to be relative/absolute file paths referring to all assemblies that should be temporarily registered in GAC. Please note that only strongly named assemblies are accepted.当前 EasyHook是怀着每个注入程序集包括所有的组件都在全局程序集缓存中(GAC).这是因为CLR将只在与当前应用主目录相关的当前目录程序集和GAC中搜索程序集,而GAC因此一个目标进程通常不能在你注入库中访问EasyHook.EasyHook正使用引用计数确定同一程序集不同的应用能被管理和安装。以下将注册所有的EasyHook组件和两个所需注入的用户程序集到GAC中。首先暂时在GAC中注册。请注意,只有强命名应用才可以。Config.Register(文件访问监视类演示程序.,FileMon.exe,FileMonInject.dll); It is guaranteed that your libraries will be removed from GAC if the injecting process is being terminated in all common cases. Of course there are some rare exceptions, for example if you shutdown your PC by disconnecting the power cable. In such a case the assemblies will remain in the GAC, forever, which is no bad thing in end-user scenarios but truly during development. You may use the Gacutil.exe that ships with Visual Studio to remove all temporary GAC assemblies. 当注入进程在所有普通情况下终止时保证你的库会从GAC中移除。当然会有很少的异常情况,例如,直接停电导致你的电脑关闭。这时程序集还会在GAC中,这在最终用户的情况下也不怎么糟,但在开发时不大好。你可以使用Visual Stuido的Gacutil.exe工具卸除所有临时的GAC程序集。Open the “Visual Studio Command Promt” as administrator. 以管理员身份打开“Visual Studio 命令行工具”1. Run the command: gacutil /uf EasyHook 运行命令:gacutil /uf EasyHook 2. Run additional commands for each of your assemblies that should be removed from the GAC 运行其它需要移徐出GAC程序集的命令。2.2 Windows DefenderWindows防火墙Injection will sometimes make the Windows Defender complain. This does not only apply to EasyHook, but to every library using remote thread creation for injection:注入有时会导至Windows防火墙的警告。这不仅仅是对EasyHook,几乎使用远程线程注入的所有库都会这样:Windows Defender Real-Time Protection agent has detected changes.Microsoft recommends you analyze the software that made these changesfor potential risks. You can use information about how these programsoperate to choose whether to allow them to run or remove them from yourcomputer. Allow changes only if you trust the program or the softwarepublisher. Windows Defender cant undo changes that you allow.For more information please see the following:Not ApplicableScan ID: 44726E79-4262-454E-AFED-51A30D34BF67User: Lynn-PCLynnName: UnknownID: Severity ID: Category ID: Path Found: process:pid:864;service:EasyHook64Svc;file:D:ProjectsEasyHook Debugx64EasyHook64Svc.exeAlert Type: Unclassified softwareDetection Type:Such warnings are immediately followed by information pointing out that Windows Defender has prevented a malicious attempt. I think this will vanish if you sign all executable binaries of EasyHook with AuthentiCode. Such blocking only occurs when injecting into essential system services.2.3 Injection A burden made easy2.3注入-负担变得简单了In general, library injection is one of the most complicated parts of any hooking library. But EasyHook goes further. It provides three layers of injection abstraction and your library is the fourth one. The first layer is pure, relocatable assembler code. It launches the second layer, an unmanaged C+ method. The assembler code itself is really stable. It provides extensive error information and is able to unload itself without leaving any resource leaks in the target. The C+ layer starts the managed injection loader and adjusts the targets PATH variable by adding the injecting process application base directory as first entry. This way you will have access to any file you would also have access to from your injecting process. The managed injection loader uses NET Reflection and NET Remoting to provide extensive error reports in case of failure and to find a proper entry point in your injection library. It also cares about graceful hook removal and resource cleanup. It is supported to load the same library multiple times into the same target!一般来说,库注入时所有挂接库中最复杂的部分。但是EasyHook让他不一样了。它提供了注入抽像的三个层而你的库在第四个。第一层是纯的汇编代码。它运行第二层,非托管的C+方法。汇编代码本身相当稳定。它提供很多的错误信息并能够将自己在目标中卸除不会留下资源泄露。C+层开始管理注入装载器并调整目标路径变量,通过添加进程应用主目录作为第一个入口。这样你可能访问任何你被注入进程能够访问的任何文件。托管的注入装载器使用NET反射和Net Remoting进供很多的在出错时的错误报告并发现在你注入库中的正确的入口点。它还关注挂钩的移除和资源的清除。它支持将同一个库多次的装入到同一目标中!Another complex part is run on host side. It is supported to inject libraries into other terminal sessions, system services and even through WOW64 boundaries. To you, all cases seem the same. EasyHook will automatically select the right injection procedure. If EasyHook has succeeded injection, you can be 99% sure that your library has been successfully loaded and executed. If it fails you can be 99% sure that no resource leaks are left in the target and it remains in a stable, hookable state! Nearly all possible failures are being caught and it would be like a lottery win to see a target getting crashed by library injection!另一个复杂的疗分时在托管这边运行。它支持将库注入到其它终端会话,系统服

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论