Get Environment Strings by injection[使用dll注入来获取所有的环境变量包括临时环境变量]

Hi all,

I have a idea, the solution in my before post only can get the current process's environment, so why don't we use injection, to inject the code into the desert process, then my code can retrieve out all the environments by GetEnvironmentStrings and use SendMessage function send the environment strings back to my Form and display it.

The following is my test project, and it is a x86 version, if you want inject to a x64 process, then you will need to compile the dll and client projects' target platform to x64.

http://cid-bb789f72272d4858.photos.live.com/self.aspx/2011/2011Y01M/CSWinFormInjection.zip

Since I'm not very good at injection and C++ language, this is just a simple demo. The dll is written by C++ language, since the managed code will not executed after we inject it into a process as I known. And the client is written in C# language.

And I also found a good open source project, it may help you to learn more about operate the process, but the method I used in this demo is written by myself, I don't know if this method is used in this project.

http://processhacker.sourceforge.net/

You can reference my thread:

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/dc44454b-b22b-49ed-a0e4-dfb5aaaf1905

在我处理一个MSDN的帖子的时候,注意到GetEnvironmentStrings 函数只能获取当前进程的所有环境变量(.net方法据我所知获取不到临时环境变量,但是此windows api 函数可以)。 刚开始怎么想,也没想出来到底用什么方法才能获取到其他进程的环境变量,其实我也想过用C#重写codeproject上的一个C++案例,但是经过我的测试以及客户的反应,那个案例经常蹦出错误,获取不到很多进程的环境变量。

今天下午,不知道为什么,哈哈,灵光一线,不知道怎么就想到了以前写过一个DLL注入的demo。哈哈,终于让我抓到了,就是它了,真是梦里寻它千百度,蓦然回首,这主意就在我的脑海深处啊,呵呵。因为据我所知managed dll在注入之后不会运行,即使你尝试使用natived代码启动CLR。所以我决定使用未曾学习过的C++代码来写这个DLL,也就是用C++调用两个API,但我没学过C++,也没用过,写这东西真把我累坏了,嘿嘿。主要是使用C++来调用GetEnvironmentStrings 函数来获取当前进程的所有环境变量,然后再调用SendMessage函数将每一条获取到的环境变量传递回client端(使用C#代码写的一个客户端,专门用来将DLL注入到进程中的一个demo),并使得client端将收到的事件中的消息解析出来显示在Form控件里。

整个实现过程也就这样。虽然说起来就是三两句话的事,但是在我自己摸索着实现代码的时候,差不多花了我10来个小时(小弟太笨,最起码是聪明的不够明显,哈哈)。

其中花的时间最多的是在调试target platform的时候,因为刚开始未注意到这点,而使用了x86的dll,而我的机器和系统是64bit的,所以怎么注入都没有结果。后来在回家的路上突然想到了target platform这回事,回到家用我的小本本一测试,果然如此。就这样x86版本就release出来了。想使用x64版本的,你只需要重新编译次解决方案中的dll和client端为x64 target platform,这样你就可以将此dll注入到64位进程,并获取其所有的环境变量。

上面部分是我给客户的回复,整个解决方案已打包,你可以点击第一个连接进行下载,里面是完整的解决方案源码和debug时的可执行文件。

另外,今天还发现有一个开源的项目做的很不错,虽然我还没看过它里面的代码,但是看那介绍和release出来的工具很有技术性,有兴趣的朋友可以点击上面第二个链接去访问其主页。

最后那个链接是那个case的链接,有兴趣的朋友可以进去瞅瞅。

代码比较粗糙,因为时间和小弟的技术能力(从来没学过、没用过C++,注入也就知道个皮毛儿,经不起追问,没办法,没时间仔细学习下,哈哈)还有精力有限,所以大家要是看到有什么地方不好的不对的,可以尽管指出,大家一起进步嘛,呵呵。

Winking smile

脖子疼了Confused smile,不说了,找周公去了Sleeping half-moon,拜拜! 下次见。。。。。。

PS:我的同事开发了一个MSDN论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行:

MSDN论坛好帮手

posted @ 2011-02-26 03:58  Mike Dos Zhang  阅读(1255)  评论(0编辑  收藏  举报