<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>CyberCoding</title>
	<atom:link href="http://cybercoding.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cybercoding.wordpress.com</link>
	<description></description>
	<lastBuildDate>Sun, 12 Feb 2012 02:08:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='cybercoding.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>CyberCoding</title>
		<link>http://cybercoding.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://cybercoding.wordpress.com/osd.xml" title="CyberCoding" />
	<atom:link rel='hub' href='http://cybercoding.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Belajar Memory Forensic Dengan Volatility</title>
		<link>http://cybercoding.wordpress.com/2012/01/12/memory-forensic-volatility/</link>
		<comments>http://cybercoding.wordpress.com/2012/01/12/memory-forensic-volatility/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 07:11:35 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[digital artifacts]]></category>
		<category><![CDATA[directory table]]></category>
		<category><![CDATA[Forensic]]></category>
		<category><![CDATA[KdVersionBlock]]></category>
		<category><![CDATA[kernel debugger]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[volatile memory]]></category>
		<category><![CDATA[Volatility]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=152</guid>
		<description><![CDATA[Mau nulis dikit ah tentang volatility, The Volatility Framework is a completely open collection of tools, implemented in Python under the GNU General Public License, for the extraction of digital artifacts from volatile memory (RAM) samples. The extraction techniques are performed completely independent of the system being investigated but offer unprecedented visibilty into the runtime [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=152&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Mau nulis dikit ah tentang volatility,</p>
<blockquote><p>The Volatility Framework is a completely open collection of tools, implemented in Python under the GNU General Public License, for the extraction of digital artifacts from volatile memory (RAM) samples. The extraction techniques are performed completely independent of the system being investigated but offer unprecedented visibilty into the runtime state of the system. The framework is intended to introduce people to the techniques and complexities associated with extracting digital artifacts from volatile memory samples and provide a platform for further work into this exciting area of research.</p></blockquote>
<p style="text-align:center;">lengkap tentang volatility anda bisa lansung buka di websitenya :<br />
<a title="volatility" href="https://www.volatilesystems.com/default/volatility"> https://www.volatilesystems.com/default/volatility</a><br />
atau project googlenya di :<br />
<a title="volatility" href="http://code.google.com/p/volatility/" target="_blank"> http://code.google.com/p/volatility/</a><br />
Atau Blognya di :<br />
<a title="volatility" href="http://volatility.tumblr.com" target="_blank"> http://volatility.tumblr.com</a></p>
<p><span id="more-152"></span></p>
<p>Cara Install Volatility</p>
<p><a title="volatility FullInstallation" href="http://code.google.com/p/volatility/wiki/FullInstallation" target="_blank">http://code.google.com/p/volatility/wiki/FullInstallation</a></p>
<p>Dan contoh pemanggilan Comand</p>
<p><a title="volatility CommandReference" href="http://code.google.com/p/volatility/wiki/CommandReference" target="_blank">http://code.google.com/p/volatility/wiki/CommandReference</a></p>
<p>Sudah install volatility nya ? sudah check comand-nya ? bagaimana menurut anda tools satu ini ? hebat kan <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> . Pertanyaannya bagaimana sih volatility mendapatkan informasi &#8211; informasi tersebut, ada yang tau ?</p>
<p>Coba panggil command <strong>Imageinfo, </strong>dan anda akan mendapatkan hasil seperti berikut :</p>
<p><a href="http://cybercoding.files.wordpress.com/2012/01/untitled.png"><img class="size-full wp-image-156 aligncenter" title="Untitled" src="http://cybercoding.files.wordpress.com/2012/01/untitled.png?w=640" alt=""   /></a></p>
<p>Beberapa informasi yang kita dapat adalah DTB (<em>Directory Table Base</em>), KDBG (<em>KDDEBUGGER_DATA</em>), KPCR ( <em>Kernel Processor Control Region</em><em>).</em></p>
<p><strong><em>Directory Table base</em></strong> atau singkatnya <strong>DTB</strong> adalah lokasi pyshical dari Page Directory. Lokasi ini sangat penting diketahui karena digunakan untuk melakukan conversi virtualaddress ke pyshical address. Apa itu virtual address apa itu pyshical address dan bagaimana cara menkonversinya ? coba baca di <a title="Windows Memory Management" href="http://www.intellectualheaven.com/Articles/WinMM.pdf" target="_blank">http://www.intellectualheaven.com/Articles/WinMM.pdf</a></p>
<p style="text-align:center;"><a title="Windows Memory Management" href="http://www.intellectualheaven.com/Articles/WinMM.pdf" target="_blank"><br />
</a></p>
<p><strong>KDBG </strong>adalah lokasi dari <em>KDDEBUGGER_DATA</em>. <em>KDDEBUGGER_DATA </em>(32 / 64) adalah stucture data yang digunakan oleh kernel debugger untuk memudahkan mengambil informasi tentang operasi system.  Ada banyak informasi penting yang bisa kita dapatkan dari KDDEBUGGER_DATA diantaranya :</p>
<ul>
<li><strong>PsLoadedModuleList, </strong>digunakan untuk mengambil informasi tentang loaded modules atau driver.</li>
<li><strong>PsActiveProcessHead</strong> adalah pointer ke awal list dari processes active yang mana tiap Entry dari list ini adalah pointer ke EPROCESS.  EPROCESS itu sendiri adalah structure yang menyimpan semua informasi tentang suatu process mulai dari ProcessID, ImageBase (logical address dari loaded Image), Object yang digunakan, Virtual Memory, thread, dan lain2.</li>
</ul>
<p style="text-align:center;"><a href="http://cybercoding.files.wordpress.com/2012/01/list.png"><img class=" wp-image-156 aligncenter" title="Untitled" src="http://cybercoding.files.wordpress.com/2012/01/list.png?w=395&#038;h=173" alt="" width="395" height="173" /></a></p>
<p style="text-align:center;"><a href="http://cybercoding.files.wordpress.com/2012/01/eprocess.png"><img class="alignnone size-full wp-image-161" title="EPRocess" src="http://cybercoding.files.wordpress.com/2012/01/eprocess.png?w=640" alt=""   /></a></p>
<ul>
<li><strong> PspCidTable </strong>adalah table yang menyimpan informasi handle dari active process dan thread. Beberapa antirootkit program menggunakan informasi handle table ini untuk mendeteksi hidden process  dengan methode unlink (DKOM).</li>
</ul>
<p><a href="http://cybercoding.files.wordpress.com/2012/01/pspcidtable.png"><img class="aligncenter size-full wp-image-166" title="PspCidTable" src="http://cybercoding.files.wordpress.com/2012/01/pspcidtable.png?w=640" alt=""   /></a></p>
<p>Untuk mendapatkan lokasi dari KDBG, ada beberapa methode yang dilakukan volatility :</p>
<ul>
<li>Melakukan Scanning dengan pattern &#8220;KDBG&#8221; yang mana adalah Magic untuk mencari keberadaan DBGKD_DEBUG_DATA_HEADER (KDBG).</li>
<li>Mengambil infromasinya pada KPCR (about KPCR see in next). Yang mana korelasinya adalah pada KPCR structure terdapat field bernama &#8220;KdVersionBlock&#8221;. KdVersionBlock merupakan pointer ke lokasi stucture DBGKD_GET_VERSION. DBGKD_GET_VERSION memiliki field DebuggerDataList yang mana akan merujuk ke <em>KDDEBUGGER_DATA.</em></li>
</ul>
<div><em><a href="http://cybercoding.files.wordpress.com/2012/01/kpcr.png"><img class="aligncenter size-full wp-image-168" title="KPCR" src="http://cybercoding.files.wordpress.com/2012/01/kpcr.png?w=640" alt=""   /></a></em></div>
<div>
<p><strong>KPCR </strong>( Kernel Processor Control Region) adalah data structure yang digunakan oleh windows kernel untuk menyimpan informasi tentang processor yang ada. Lokasi dari <strong>KPCR </strong>merupakan keharusan dalam memory forensic karena informasi yang terkandung dalamnya. Liat bagaimana dengan <strong>KPCR </strong>kita bisa mendapatkan lokasi KDDEBUGGER_DATA yang membuat kita mendapatkan informasi lanjutan seperti process, modules, dan handle.</p>
</div>
<p><em>Tulis apa lagi nih ??? udahan ahh ngantuk. Thankyou yah buat yang baca. Maaf Bila ada kesalahan dalam tulisan ini (banyak pastinya hahaahah, harap maklum).</em><em></em><br />
<em> </em></p>
<p>Reference</p>
<p><em>http://amnesia.gtisc.gatech.edu/~moyix/tpcompare/withnums/</em><em></em></p>
<p><em>http://www.evild3ad.com/?p=1136</em><em></em></p>
<p><em>http://moyix.blogspot.com/2008/04/finding-kernel-global-variables-in.html</em><em></em></p>
<p><em>http://hi.baidu.com/cr0_3/blog/item/951555208f167442925807f7.html</em><em></em></p>
<p><em>http://antirootkit.wordpress.com/page/2/</em><em></em></p>
<p><em>http://blog.schatzforensic.com.au/2010/07/finding-object-roots-in-vista-kpcr/</em><em></em></p>
<p><em>http://mnin.blogspot.com/2011/04/investigating-windows-threads-with.html</em><em></em></p>
<p><em>http://x9090.blogspot.com/2009/09/doc-windbg-hiding-processes-with-dkom.html</em><em></em></p>
<p><em>http://forum.sysinternals.com/</em><em></em></p>
<p><em>http://uninformed.org</em><em></em></p>
<p><em>http://blog.csdn.net/misterliwei/article/details/1660819 </em><em></em></p>
<p><em>http://memogaki.wordpress.com/2011/10/01/kpcr/</em><em></em></p>
<p><em>BOOK &#8211; Microsoft.Windows.Internals.Fourth.Edition</em><em></em></p>
<p><em>dan banyak lagi sumber lainnya (lupa), coba cari google <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </em><em></em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/152/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=152&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2012/01/12/memory-forensic-volatility/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>

		<media:content url="http://cybercoding.files.wordpress.com/2012/01/untitled.png" medium="image">
			<media:title type="html">Untitled</media:title>
		</media:content>

		<media:content url="http://cybercoding.files.wordpress.com/2012/01/list.png" medium="image">
			<media:title type="html">Untitled</media:title>
		</media:content>

		<media:content url="http://cybercoding.files.wordpress.com/2012/01/eprocess.png" medium="image">
			<media:title type="html">EPRocess</media:title>
		</media:content>

		<media:content url="http://cybercoding.files.wordpress.com/2012/01/pspcidtable.png" medium="image">
			<media:title type="html">PspCidTable</media:title>
		</media:content>

		<media:content url="http://cybercoding.files.wordpress.com/2012/01/kpcr.png" medium="image">
			<media:title type="html">KPCR</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] Method for Detect AntiVirus Emulator</title>
		<link>http://cybercoding.wordpress.com/2011/12/12/detect-antivirus-emulator/</link>
		<comments>http://cybercoding.wordpress.com/2011/12/12/detect-antivirus-emulator/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 23:01:15 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Antivirus]]></category>
		<category><![CDATA[Code Virtualization]]></category>
		<category><![CDATA[Emulator]]></category>
		<category><![CDATA[Image]]></category>
		<category><![CDATA[Malware]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[PEB]]></category>
		<category><![CDATA[Sections]]></category>
		<category><![CDATA[Virus]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=135</guid>
		<description><![CDATA[Emulator adalah ruang virtual pada antivirus yang digunakan untuk mengeksekusi malware. Gunanya adalah agar antivirus dapat mengetahui behavior dari virus tampa harus menginfeksi real system. Selain itu emulator juga digunakan sebagai generic unpacking bagi malware &#8211; malware yang diproteksi program pelindung seperti crypter/packer. Sangat critical fungsi dari emulator ini, bahkan sudah menjadi keharusan suatu antivirus [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=135&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Emulator adalah ruang virtual pada antivirus yang digunakan untuk mengeksekusi malware. Gunanya adalah agar antivirus dapat mengetahui behavior dari virus tampa harus menginfeksi real system. Selain itu emulator juga digunakan sebagai generic unpacking bagi malware &#8211; malware yang diproteksi program pelindung seperti crypter/packer. Sangat critical fungsi dari emulator ini, bahkan sudah menjadi keharusan suatu antivirus mempunyai engine emulator didalamnya. Kalau saja antivirus buatan anda tidak ada emulatornya saya sih cuman bilang bershowerlah* (ikutan kata pocoong).  Meski demikian membuat emulator tidaklah mudah, tantangan terberat adalah bagaimana membuat ruang virtual ini tampak bagai real system bagi virus. Nah pada tulisan ini saya menshare methode dan snippet code yang bisa digunakan untuk mendeteksi emulator dari AV.</p>
<p><span id="more-135"></span></p>
<p>Tiap melakukan load image, windows loader akan memulainya dengan membuat section dan mengakhiri dengan menyimpan informasi loaded image pada PEB (Process Environtment Block).</p>
<p>Process pembuatan section kita bisa liat pada doxygen reactos (for apicall)  yang  adalah sebagai berikut :</p>
<blockquote><p>LdrpLoadDll</p>
<p><a href="http://doxygen.reactos.org/dd/d83/ntdllp_8h_a297208bd9a920c295937d755afc40387.html#a297208bd9a920c295937d755afc40387">http://doxygen.reactos.org/dd/d83/ntdllp_8h_a297208bd9a920c295937d755afc40387.html#a297208bd9a920c295937d755afc40387</a></p>
<p>LdrpLoadDll akan memanggil LdrpMapDll</p>
<p><a href="http://doxygen.reactos.org/dd/d83/ntdllp_8h_a2108d522b1162cb346c676b0ddc5272e.html#a2108d522b1162cb346c676b0ddc5272e">http://doxygen.reactos.org/dd/d83/ntdllp_8h_a2108d522b1162cb346c676b0ddc5272e.html#a2108d522b1162cb346c676b0ddc5272e</a></p>
<p>LdrpMapDll akan memanggil LdrpCreateDllSection</p>
<p><a href="http://doxygen.reactos.org/d8/d55/ldrutils_8c_abb3a063e894fe6a8bfce3a541d4af034.html#abb3a063e894fe6a8bfce3a541d4af034">http://doxygen.reactos.org/d8/d55/ldrutils_8c_abb3a063e894fe6a8bfce3a541d4af034.html#abb3a063e894fe6a8bfce3a541d4af034</a></p>
<p>LdrpCreateDllSection  akan memanggil NtCreateSection</p></blockquote>
<p>pada api NtCreateSection terdapat parameter &#8220;FileHandle&#8221; yang mana disimpan sebagai informasi file dari section. informasi ini sangat berguna untuk mengetahui file path dari section saat melakukan query memory (NtQueryVirtualMemory dengan parameter MemorySectionName). Pada PEB juga disimpan mengenai image filename yang terletak pada ldr data.</p>
<p>Berdasarkan informasi diatas maka saya mencoba melakukan comparasi filaname yang terletak pada PEB-LDR dan filename yang terletak pada section information. Hasilnya ternyata pada beberapa emulator (tested with kaspersky) nilai kedua filename ini berbeda, alasannya karena emulator kaspersky hanya mengemulasikan PEB tidak untuk section object .</p>
<p><pre class="brush: plain;">
program Project1;

uses Windows, jwaNative, NcxNtTeb;

function ExtractFileName(FullName: String): String;
var
i, n: integer;
begin
  result := '';
  n := Length(FullName);
  Result := FullName;
  for i := n downto 1 do if FullName[i] = '\' then break;
  if i &gt; 1 then Result := Copy(FullName, i+1, n-i);
end;

function NtSuccess (Stat: LongInt): Boolean;
begin
  Result := Stat &gt;= 0;
end;

Function GetModuleFileNameByAddres(ph:THandle; Address : DWord):String;
var
  mSize,back: dword;
  mPtr: pointer;
  St: LongInt;
begin
  result := '';
  mSize := 512;
  mPtr := AllocMem(mSize);
  St := NtQueryVirtualMemory(ph, Pointer(Address), MemorySectionName, mPtr,mSize,@back);
  if NtSuccess(st) then result := PMEMORY_SECTION_NAME(mPtr).SectionFileName.Buffer;
  FreeMem(mPtr,mSize);
end;

function GetPEB(): Pointer;
asm
  mov eax, large fs:30h
  retn
end;

Function CheckEmulator:Boolean;
var
  pb: PPeb32;
  ldrdata: PPebLdrData32;
  ldrEntry: PLdrDataTableEntry32;
  name1, name2: String;
begin
  //get peb
  pb := GetPEB;
  //get ldr
  ldrdata := pb^.Ldr;
  //get first ldr entry
  ldrEntry := ldrdata^.InLoadOrderModuleList.Flink;
  //get section filename
  name1 := ExtractFileName(GetModuleFileNameByAddres(thandle(-1), DWORD(ldrEntry^.DllBase)));
  //get PEB Image filename
  name2 := ExtractFileName(PWideChar(ldrEntry.FullDllName.Buffer));
  //Compare
  result := name1=name2;
end;

begin
  if not CheckEmulator then messagebox(0, nil, nil, mb_ok);
end.

</pre></p>
<p>Scanyou result test<br />
<a title="Before" href="http://scan4you.net/result.php?id=c3408_11egap" target="_blank">Before</a><br />
<a title="after" href="http://scan4you.net/result.php?id=dc46a_11dtd3" target="_blank">After</a></p>
<p>terakhir saya tidak bertanggung jawab atas penggunaan kode diatas karena tulisan ini saya buat hanya sebagai dokumentasi hasil research tentang bagaimana mendeteksi emulator. Semoga kedepannya av developer dapat lebih menyempurnakan emulatornya..</p>
<p>thanks.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=135&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/12/12/detect-antivirus-emulator/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] Calculate Entropy PE Section</title>
		<link>http://cybercoding.wordpress.com/2011/12/02/delphi-calculate-entropy-pe-section/</link>
		<comments>http://cybercoding.wordpress.com/2011/12/02/delphi-calculate-entropy-pe-section/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 07:37:07 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[CalculateEntropy]]></category>
		<category><![CDATA[Entropy]]></category>
		<category><![CDATA[ImageNtHeaders]]></category>
		<category><![CDATA[PE]]></category>
		<category><![CDATA[Portable Executable]]></category>
		<category><![CDATA[Section]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=131</guid>
		<description><![CDATA[Just read some post on ic0de about calculate entropy http://www.ic0de.org/showthread.php?10804-Calcuate-Entropy and http://www.ic0de.org/showthread.php?10902-CalcEntropyForBuffer-produces-access-violation&#038;p=54084#post54084 think about create snippet for calculate entropy of specific PE section, use steve10120 snippet ofcourse and example use<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=131&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Just read some post on ic0de about calculate entropy </p>
<p>http://www.ic0de.org/showthread.php?10804-Calcuate-Entropy</p>
<p>and </p>
<p>http://www.ic0de.org/showthread.php?10902-CalcEntropyForBuffer-produces-access-violation&#038;p=54084#post54084</p>
<p>think about create snippet for calculate entropy of specific PE section, use steve10120 snippet ofcourse <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><span id="more-131"></span></p>
<p><pre class="brush: plain;">
type
  TImageOptionalHeader64 = packed record
    Magic                       : WORD;
    MajorLinkerVersion          : BYTE;
    MinorLinkerVersion          : BYTE;
    SizeOfCode                  : DWORD;
    SizeOfInitializedData       : DWORD;
    SizeOfUninitializedData     : DWORD;
    AddressOfEntryPoint         : DWORD;
    BaseOfCode                  : DWORD;
    ImageBase                   : int64;
    SectionAlignment            : DWORD;
    FileAlignment               : DWORD;
    MajorOperatingSystemVersion : WORD;
    MinorOperatingSystemVersion : WORD;
    MajorImageVersion           : WORD;
    MinorImageVersion           : WORD;
    MajorSubsystemVersion       : WORD;
    MinorSubsystemVersion       : WORD;
    Win32VersionValue           : DWORD;
    SizeOfImage                 : DWORD;
    SizeOfHeaders               : DWORD;
    CheckSum                    : DWORD;
    Subsystem                   : WORD;
    DllCharacteristics          : WORD;
    SizeOfStackReserve          : int64;
    SizeOfStackCommit           : int64;
    SizeOfHeapReserve           : int64;
    SizeOfHeapCommit            : int64;
    LoaderFlags                 : DWORD;
    NumberOfRvaAndSizes         : DWORD;
    DataDirectory               : array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of IMAGE_DATA_DIRECTORY;
  end;
  PImageOptionalHeader64 = ^TImageOptionalHeader64;

const
  IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b;  // 32bit PE file
  IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20b;  // 64bit PE file
  IMAGE_NT_HEADER_OFFSET_OFFSET = $3c;

function Align(Value, Align: Cardinal): Cardinal;
begin
  if ((Value mod Align) = 0) then
    Result := Value
  else
    Result := ((Value + Align - 1) div Align) * Align;
end;

{
CalcEntropyForBuffer from steve10120
http://www.ic0de.org/showthread.php?10804-Calcuate-Entropy
}
function CalcEntropyForBuffer(Buffer:Pointer; BufferSize:DWORD):Double;
const
  DbLog:   Double = 1.4426950408889634073599246810023;
var
  Entropy:  Double;
  Entries:  array[0..255] of DWORD;
  i:        DWORD;
  Temp:     Double;
begin
  Entropy := 0.00;
  ZeroMemory(@Entries, SizeOf(Entries));
  for i := 0 to (BufferSize - 1) do
    Inc(Entries[PByte(DWORD(Buffer) + i)^]);
  for i := 0 to 255 do
  begin
    Temp := Entries[i] / BufferSize;
    if (Temp &gt; 0) then
      Entropy := Entropy + Temp * (Ln(Temp) * DbLog);
  end;
  Result := Entropy;
end;

Function CalculateEntropy(pFile:Pointer; SecNumber:Word; var Entropy:Double):Boolean;
var
  pINH:       PImageNtHeaders;
  pISH:       PImageSectionHeader;
  ScLoc:      DWord;
  ScSize:     DWord;
begin
  result := false;

  try
    {check Dos Header}
    if (PWord(pFile)^ &lt;&gt; IMAGE_DOS_SIGNATURE) then exit;

    {Get NT Header}
    pINH := (Pointer(NativeUint(pFile) +
            NativeUint(Pointer(NativeUint(pFile) + IMAGE_NT_HEADER_OFFSET_OFFSET)^)));

    {check NT Header}
    if (pINH^.Signature &lt;&gt; IMAGE_NT_SIGNATURE) then exit;

    { get first section }
    if pINH^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
      pISH := PImageSectionHeader(NativeUint(@pINH^.OptionalHeader) + sizeOf(TImageOptionalHeader64))
    else
      pISH := PImageSectionHeader(NativeUint(@pINH^.OptionalHeader) + sizeOf(TImageOptionalHeader));

    { get Target section }
    dec(SecNumber); //section number start from 0
    pISH := Pointer(NativeUint(pISH)+ (SecNumber * Sizeof(TImageSectionHeader)));

    { get current section address at file }
    ScLoc := Align(pISH^.PointerToRawData, pINH^.OptionalHeader.FileAlignment);

    { get current section size }
    ScSize := pISH^.Misc.VirtualSize;
    if (ScSize = 0) then ScSize := pISH^.SizeOfRawData;

    { Calc Entropy Section, thanks for steve10120 }
    Entropy := CalcEntropyForBuffer(Pointer(NativeUint(PFile) + ScLoc), ScSize);
    result := true;
  Except
    {Pointer read exception}
  end;
end;
</pre></p>
<p>and example use</p>
<p><pre class="brush: plain;">
function FileToPtr(szFilePath:string; var pData:Pointer; var dwSize:DWORD):Boolean;
var
  hFile:  DWORD;
  dwNull: DWORD;
begin
  Result := FALSE;
  hFile := CreateFile(PChar(szFilePath), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
  if hFile &lt;&gt; INVALID_HANDLE_VALUE then
  begin
    dwSize := GetFileSize(hFile, nil);
    GetMem(pData, dwSize);
    SetFilePointer(hFile, 0, nil, FILE_BEGIN);
    if ReadFile(hFile, pData^, dwSize, dwNull, nil) then
      Result := TRUE;
    CloseHandle(hFile);
  end;
end;

var
  pFile:Pointer;
  dwSize:DWORD;
  Entropy: Double;
begin
  if FileToPtr(paramstr(0), pFile, dwSize) then begin
    if CalculateEntropy(pfile, 1, Entropy) then
      codesite.Send('Entropy', Entropy);
    FreeMem(pFile, dwSize);
  end;
end.
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=131&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/12/02/delphi-calculate-entropy-pe-section/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] Multi Pattern Search &#8211; WUManber Algoritm</title>
		<link>http://cybercoding.wordpress.com/2011/11/29/delphi-multipattern-search-wumanber-algoritm/</link>
		<comments>http://cybercoding.wordpress.com/2011/11/29/delphi-multipattern-search-wumanber-algoritm/#comments</comments>
		<pubDate>Tue, 29 Nov 2011 04:30:44 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[MultiPattern]]></category>
		<category><![CDATA[Pattern]]></category>
		<category><![CDATA[Search]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Suffix]]></category>
		<category><![CDATA[WuManber]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=128</guid>
		<description><![CDATA[Mencari keberadaan satu kata dalam suatu text mungkin hall biasa, tapi bagaimana apabila anda akan mencari beberapa (banyak kata) dalam satu text ? heh perlu cara khusus untuk bisa mendapatkan hasil yang cepat. Nah dari beberapa algoritm multipattern search yang saya tau, algoritm dari WuManber merupakan salah satu yang tercepat. Lengkapnya tentang algoritm WuManber cari [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=128&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Mencari keberadaan satu kata dalam suatu text mungkin hall biasa, tapi bagaimana apabila anda akan mencari beberapa (banyak kata) dalam satu text ? heh perlu cara khusus untuk bisa mendapatkan hasil yang cepat. Nah dari beberapa algoritm multipattern search yang saya tau, algoritm dari WuManber merupakan salah satu yang tercepat. Lengkapnya tentang algoritm WuManber cari di google yah :p</p>
<p>here u go the code<br />
<span id="more-128"></span></p>
<p><pre class="brush: plain;">
unit U_MatchWU;

interface
uses
  Windows, Classes;

const
 MAXHASH = $7FFF;
 MASK = $1F;

type
  PMatchItem = ^TMatchItem;
  TMatchItem = record
    Len: WORD;
    Pattern: PByte;
    InfoIndex: Integer;
  end;
  TMatchArray = Array of PMatchItem;
  THashArray  = Array Of Integer;

  TMatchWU = class
  Private
    FCount: Integer;
    suffix: Array of Integer;
    ShiftList: Array[0..MAXHASH] of Integer;
    HashList: Array[0..MAXHASH] of THashArray;
    ItemList: TMatchArray;
    LMin: integer;
    B: integer;
  Public
    constructor Create;
    Destructor Destroy; override;
    Function AddPattern(Pattern: AnsiString; InfoIndex: Integer):Boolean;
    Procedure InitHash;
    Function Search(Buffer: PByte; SzSize: LongInt; Var InfoIndex:Integer):Integer;
  end;

implementation

Function GetByte(Pattern:PByte; Loc:Integer):Integer;
begin
  Result := PByte(Pointer(Integer(Pattern)+Loc))^;
end;

constructor TMatchWU.Create;
var
i: integer;
begin
  inherited create;
  FCount := 0;
  lmin := High(Integer);
  for i := 0 to MAXHASH do begin
    ShiftList[i] := 0;
    Setlength(HashList[i], 0);
  end;
  Setlength(suffix, FCount);
  Setlength(ItemList, FCount);
end;

Destructor TMatchWU.Destroy;
var
i : integer;
begin
  for i := 0 to MAXHASH do begin
    setlength(HashList[i], 0);
  end;
  for i := 0 to FCount-1 do begin
    if assigned(ItemList[i]) then begin
      with ItemList[i]^ do begin
        if assigned(Pattern) then FreeMem(Pattern, len+1);
      end;
      FreeMem(ItemList[i]);
    end;
  end;
  setlength(ItemList, 0);
  setlength(suffix, 0);
  inherited Destroy;
end;

Function TMatchWU.AddPattern(Pattern: AnsiString; InfoIndex: Integer):Boolean;
var
  Item: PMatchItem;
begin
  result := false;
  Item := AllocMem(SizeOf(TMatchItem));
  if Assigned(Item) then begin
    Item^.Len := (Length(Pattern) div 2);
    if (Item^.Len &gt; 0) then begin
      try
        Item^.Pattern := AllocMem(Item^.Len);
        HexToBin(Pansichar(Pattern), Item^.Pattern, Length(Pattern));
        Item^.InfoIndex := InfoIndex;
        Dec(Item^.Len);
        inc(FCount);
        SetLength(ItemList, FCount);
        ItemList[FCount-1] := Item;
        result := true;
      except
      end;
    end;
    if (result = false) and Assigned(Item) then FreeMem(Item);
  end;
end;

Procedure TMatchWU.InitHash;
var
  i, def, pl, hi, h: Integer;
begin
  {calculated shorted pattern length}
  for i := 0 to FCount -1 do begin
    if lmin &gt; ItemList[i]^.Len then lmin := ItemList[i]^.Len;
  end;

  {calculated shift count}
  if lmin = 1 then B := 1
  else if (lmin &gt; 2) and (lmin*FCount &gt; 400) then B := 3
  else B := 2;
  def := lmin - B + 1;

  {Insert default shift}
  for i := 0 to MAXHASH do ShiftList[i] := def;

  {Configure Suffix List}
  Setlength(suffix, FCount);
  for i := 0 to FCount - 1 do begin
    pl := ItemList[i]^.Len;
    if B=1 then suffix[i] := GetByte(ItemList[i]^.Pattern, pl-lmin)
    else suffix[i] := (GetByte(ItemList[i]^.Pattern, pl-lmin) shl 8) + GetByte(ItemList[i]^.Pattern, pl-lmin+1);
  end;

  {Configure Hash List}
  for i := 0 to FCount - 1 do begin
    pl := ItemList[i]^.Len;
    for hi := (pl - lmin + B)-1 to (pl - 1) do begin
      h := GetByte(ItemList[i]^.Pattern, hi) AND MASK;
      if (B &gt;= 2) then h := (h shl 5) + (GetByte(ItemList[i]^.Pattern, hi-1) and MASK);
      if (B &gt;= 3) then h := (h shl 5) + (GetByte(ItemList[i]^.Pattern, hi-2) and MASK);
      if (ShiftList[h] &gt; pl-hi) then ShiftList[h] := pl-hi;
    end;
    h := GetByte(ItemList[i]^.Pattern, pl) AND MASK;
    if (B &gt;= 2) then h := (h shl 5) + (GetByte(ItemList[i]^.Pattern, pl-1) and MASK);
    if (B &gt;= 3) then h := (h shl 5) + (GetByte(ItemList[i]^.Pattern, pl-2) and MASK);
    ShiftList[h] := 0;
    Setlength(HashList[h], Length(HashList[h])+1);
    HashList[h][Length(HashList[h])-1] := i;
  end;
end;

Function TMatchWU.Search(Buffer: PByte; SzSize: LongInt; Var InfoIndex:Integer):Integer;
var
  i, h, j, k, l: Integer;
  TextSuft: Integer;
begin
  result := -1;
  if lmin = High(Integer) then exit;

  {shorted pattern as starting point}
  i := lmin;
  while (i &lt;= SzSize) do begin

    {Get Hash}
    h := GetByte(Buffer, i) AND MASK;
    if B &gt;= 2 then h := (h shl 5) + (GetByte(Buffer, i-1) and MASK);
    if B &gt;= 3 then h := (h shl 5) + (GetByte(Buffer, i-2) and MASK);
    if (ShiftList[h] = 0) then begin

      {Get Suffix}
      if B=1 then TextSuft := GetByte(Buffer, i-lmin)
      else TextSuft := (GetByte(Buffer, i-lmin) shl 8) + GetByte(Buffer, i-lmin + 1);
      if (Length(HashList[h]) &lt;&gt; 0) then begin
        for j := 0 to Length(HashList[h]) - 1 do begin

          {Check if Suffix same}
          k := HashList[h][j];
          if (suffix[k] = TextSuft) and (i &gt;= ItemList[k]^.Len) then begin

            {Check if pattern same}
            l := 0;
            while (l &lt;= ItemList[k]^.Len) and (GetByte(Buffer, i-l) = GetByte(ItemList[k]^.Pattern, ItemList[k]^.Len-l)) do inc(l);
            if (l-1 = ItemList[k]^.Len) then begin

              {get the result}
              InfoIndex := ItemList[k]^.InfoIndex;
              result := i-ItemList[k]^.Len;
              exit;
            end;
          end;
        end;
      end;
      inc(i);
    end else inc(i, ShiftList[h]);
  end;
end;

end.

</pre></p>
<p>u can used it like this<br />
<pre class="brush: plain;">
program Project1;


uses
  Windows, SysUtils, codesitelogging,
  U_MatchWU in 'U_MatchWU.pas';

function FileToAnsiString(sPath:string; var bFile:AnsiString):Boolean;
var
hFile:  THandle;
dSize:  DWORD;
dRead:  DWORD;
begin
 Result := FALSE;
 hFile := CreateFile(PChar(sPath), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
 if hFile &lt;&gt; 0 then
 begin
  dSize := GetFileSize(hFile, nil);
  SetFilePointer(hFile, 0, nil, FILE_BEGIN);
  SetLength(bFile, dSize);
  if ReadFile(hFile, bFile[1], dSize, dRead, nil) then
   Result := TRUE;
  CloseHandle(hFile);
 end;
end;

var
  value:AnsiString;
  Matcher: TMatchWU;
  i, infoIndex:Integer;
begin
  FileToAnsiString(paramstr(0), value);
  codesite.SendMemoryAsHex('value', @value[1], length(value));
  Matcher := TMatchWU.Create;
  try
    Matcher.AddPattern('546869732070726F', 1);
    Matcher.AddPattern('504500004C010A00', 2);
    Matcher.InitHash;
    i := Matcher.Search(@value[1], length(value), infoIndex);
    codesite.Send('%x : %d', [i, infoIndex]);
  finally
    Matcher.Free;
  end;
end.

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/128/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=128&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/11/29/delphi-multipattern-search-wumanber-algoritm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] Get MD5 Loaded Module</title>
		<link>http://cybercoding.wordpress.com/2011/11/21/delphi-get-md5-loaded-module/</link>
		<comments>http://cybercoding.wordpress.com/2011/11/21/delphi-get-md5-loaded-module/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 00:59:11 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[BaseDllName]]></category>
		<category><![CDATA[NTAPI]]></category>
		<category><![CDATA[PE]]></category>
		<category><![CDATA[PEB]]></category>
		<category><![CDATA[Portable Executable]]></category>
		<category><![CDATA[VirtualMemory]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=123</guid>
		<description><![CDATA[Terkadang kita butuh mengambil checksum atau hash dari module/dll yang terload dengan tujuan menggunakannya untuk berbagai keperluan, ex Anti Tampering pada game &#60;- . Nah snippet berikut akan mengenumerasi semua module yang terload (PEB) dan mengambil md5 dari first section, semoga berguna . hmm btw untuk module enumerasi anda bisa menggunakan methode lain misalkan dengan [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=123&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Terkadang kita butuh mengambil checksum atau hash dari module/dll yang terload dengan tujuan menggunakannya untuk berbagai keperluan, ex Anti Tampering pada game &lt;- . Nah snippet berikut akan mengenumerasi semua module yang terload (PEB) dan mengambil md5 dari first section, semoga berguna <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> .</p>
<p><span id="more-123"></span></p>
<p><pre class="brush: plain;">
program MemMd5;

uses
  Windows,
  Sysutils,
  JwaNative,
  JwaNtStatus,
  JwaWinType,
  NcxTypes,
  NcxNtDef,
  NcxNtTeb,
  codesitelogging,
  U_UnionApi,
  U_Md5;

type
  PROCESS_BASIC_INFORMATION = record
    ExitStatus: Cardinal;
    PebBaseAddress: PVOID;
    AffinityMask: Cardinal;
    BasePriority: Cardinal;
    UniqueProcessId: Cardinal;
    InheritedFromUniqueProcessId: Cardinal;
  end;
  TProcessBasicInformation = PROCESS_BASIC_INFORMATION;
  PProcessBasicInformation = ^TProcessBasicInformation;

  TImageOptionalHeader64 = packed record
    Magic                       : WORD;
    MajorLinkerVersion          : BYTE;
    MinorLinkerVersion          : BYTE;
    SizeOfCode                  : DWORD;
    SizeOfInitializedData       : DWORD;
    SizeOfUninitializedData     : DWORD;
    AddressOfEntryPoint         : DWORD;
    BaseOfCode                  : DWORD;
    ImageBase                   : int64;
    SectionAlignment            : DWORD;
    FileAlignment               : DWORD;
    MajorOperatingSystemVersion : WORD;
    MinorOperatingSystemVersion : WORD;
    MajorImageVersion           : WORD;
    MinorImageVersion           : WORD;
    MajorSubsystemVersion       : WORD;
    MinorSubsystemVersion       : WORD;
    Win32VersionValue           : DWORD;
    SizeOfImage                 : DWORD;
    SizeOfHeaders               : DWORD;
    CheckSum                    : DWORD;
    Subsystem                   : WORD;
    DllCharacteristics          : WORD;
    SizeOfStackReserve          : int64;
    SizeOfStackCommit           : int64;
    SizeOfHeapReserve           : int64;
    SizeOfHeapCommit            : int64;
    LoaderFlags                 : DWORD;
    NumberOfRvaAndSizes         : DWORD;
    DataDirectory               : array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of IMAGE_DATA_DIRECTORY;
  end;
  PImageOptionalHeader64 = ^TImageOptionalHeader64;

  PImageBaseRelocation = ^TImageBaseRelocation;
  _IMAGE_BASE_RELOCATION = packed record
    VirtualAddress: DWORD;
    SizeOfBlock: DWORD;
  end;
  TImageBaseRelocation = _IMAGE_BASE_RELOCATION;
  IMAGE_BASE_RELOCATION = _IMAGE_BASE_RELOCATION;

const
  IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b;  // 32bit PE file
  IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20b;  // 64bit PE file

function NtSuccess(API:AnsiString; AStatus: LongInt): Boolean; overload;
var
  error : DWord;
begin
  Result := AStatus &gt;= 0;
  if result=false then begin
    error := RtlNtStatusToDosError(AStatus);
    SetLastError(error);
    codesite.Sendwinerror('api', error);
  end;
end;

function NtSuccess(AStatus: LongInt): Boolean; overload;
begin
  Result := AStatus &gt;= 0;
end;

function NTApiCall(ApiName: AnsiString; Arg: Array of Const): DWORD; stdcall;
begin
  result := ApiCall32(ApiName, Arg);
  NtSuccess(ApiName, result);
end;

Function GetModuleString(Buff:PWideChar):string;
var
  temp:String;
  I: Integer;
begin
  SetString(temp, Buff, StrLen(Buff));
  I := LastDelimiter('.' + PathDelim + DriveDelim, temp);
  if (I &gt; 0) and (temp[I] = '.') then
    result := Copy(temp, 1, I+3)
  else
    result := temp;
end;

function Align(Value, Align: Cardinal): Cardinal;
begin
  if ((Value mod Align) = 0) then
    Result := Value
  else
    Result := ((Value + Align - 1) div Align) * Align;
end;

Function SetMemProtection(ph: THandle; lpAddress: Pointer; dwSize, flNewProtect: DWORD; var OldProtect: DWORD):boolean;
var
  status: NTStatus;
begin
  Status := NTApiCall('NtProtectVirtualMemory', [
              ph,
              @lpAddress,
              @dwSize,
              flNewProtect,
              @OldProtect
            ]);

  result := NtSuccess(Status);
end;

function GetPeb32(ph : THandle; var PEB : TPeb32):Boolean;
var
  PBI           : PROCESS_BASIC_INFORMATION;
begin
  result := false;

  {Get PROCESS_BASIC_INFORMATION}
  if not NtSuccess(NTApiCall('NtQueryInformationProcess', [ph, Pointer(ProcessBasicInformation), @PBI, SizeOf(PBI), nil])) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Get PROCESS BASIC INFORMATION  ', Getlasterror);{$ENDIF}
    exit;
  end;

  {Reading PEB}
  if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, pbi.PebBaseAddress, @PEB, sizeof(PEB), nil])) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading PEB', Getlasterror);{$ENDIF}
    exit;
  end;

  result := true;
end;

function MD5FirstSectionModule(ph: Thandle; ImageBase:Pointer): String;
var
  pImage:     Pointer;
  pSection:   Pointer;
  INH:        PImageNtHeaders;
  pISH:       PImageSectionHeader;
  Scaddr:     DWord;
  ScSize:     DWord;
  Protect:    DWORD;
begin
  result := '';
  pImage := AllocMem($1000);
  try

    { Read Image }
    if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, ImageBase, pImage, $1000, nil])) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading Image ', Getlasterror);{$ENDIF}
      exit;
    end;

    { Check Dos Header }
    if (PImageDosHeader(pImage)^.e_magic &lt;&gt; IMAGE_DOS_SIGNATURE) then exit;

    { Check PE Header }
    INH := Pointer(NativeUint(pImage) + NativeUint(PImageDosHeader(pImage)^._lfanew));
    if (INH^.Signature &lt;&gt; IMAGE_NT_SIGNATURE) then exit;

    { get first section }
    if INH^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
      pISH := PImageSectionHeader(NativeUint(@INH^.OptionalHeader) + sizeOf(TImageOptionalHeader64))
    else
      pISH := PImageSectionHeader(NativeUint(@INH^.OptionalHeader) + sizeOf(TImageOptionalHeader));

    { get section address }
    Scaddr := Align(pISH^.VirtualAddress, INH^.OptionalHeader.SectionAlignment);

    { get section size }
    ScSize := pISH^.Misc.VirtualSize;
    if (ScSize = 0) then ScSize := pISH^.SizeOfRawData;

    pSection := AllocMem(ScSize);
    try

      { get memory protection }
      SetMemProtection(ph, Pointer(NativeUint(ImageBase)+Scaddr), ScSize, PAGE_EXECUTE_READWRITE, Protect);

      { check if can access}
      if ((Protect and PAGE_NOACCESS) = PAGE_NOACCESS) then begin
        SetMemProtection(ph, Pointer(NativeUint(ImageBase)+Scaddr), ScSize, Protect, Protect);
      end else begin

        { read section }
        if NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, Pointer(NativeUint(ImageBase)+Scaddr), pSection, ScSize, nil])) then begin

          { Get MD5}
          result := MD5DigestToString(MD5Buffer(pSection^, ScSize));
        end;

        { restore the protection }
        SetMemProtection(ph, Pointer(NativeUint(ImageBase)+Scaddr), ScSize, Protect, Protect);
      end;
    finally
      FreeMem(pSection);
    end;
  finally
    FreeMem(pImage);
  end;
end;

procedure PEB32ModuleList(ph : THandle);
var
  PEB           : TPeb32;
  LdrData       : TPebLdrData32;
  LdrModule     : TLdrDataTableEntry32;
  BaseDllName   : Pointer;
  i, dwread     : DWord;
  Head,Current  : DWord;
begin
  if not GetPeb32(ph, PEB) then exit;

  { Reading LoaderData }
  if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, PEB.Ldr, @LdrData, sizeof(TPebLdrData32), @dwread])) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading LoaderData ', Getlasterror);{$ENDIF}
    exit;
  end;

  { init for enum the linked list }
  i := 0;
  Head := 0;
  Current := DWord(LdrData.InLoadOrderModuleList.Flink);

  { loop for all ldr entry or module }
  repeat

    { Reading Current entry }
    if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, Ptr(Current), @LdrModule, SizeOf(LdrModule), @dwread])) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading Current entry ', Getlasterror);{$ENDIF}
      break;
    end;

    BaseDllName := AllocMem(LdrModule.BaseDllName.Length);
    try

      { Reading BaseDllName }
      if not NtSuccess(NTApiCall('NtReadVirtualMemory', [ph, LdrModule.BaseDllName.Buffer, BaseDllName, LdrModule.BaseDllName.Length, @dwread])) then begin
        {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading BaseDllName', Getlasterror);{$ENDIF}
        break;
      end;

      codesite.send('%s | %s ',[GetModuleString(BaseDllName), MD5FirstSectionModule(ph, LdrModule.DllBase)]);
    finally
      FreeMem(BaseDllName, LdrModule.BaseDllName.Length);
    end;

    { Next Module }
    if i=0 then Head := Dword(LdrModule.InLoadOrderLinks.Blink);
    Current := Dword(LdrModule.InLoadOrderLinks.Flink);
    inc(i);
  until Current = Head;
end;


begin
  try
    PEB32ModuleList(thandle(-1));
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
</pre></p>
<p>hmm btw untuk module enumerasi anda bisa menggunakan methode lain misalkan dengan query memory.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/123/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=123&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/11/21/delphi-get-md5-loaded-module/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] Native File Read And Write Example</title>
		<link>http://cybercoding.wordpress.com/2011/11/05/delphi-native-file-read-and-write-example/</link>
		<comments>http://cybercoding.wordpress.com/2011/11/05/delphi-native-file-read-and-write-example/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 00:26:04 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Native]]></category>
		<category><![CDATA[NTAPI]]></category>
		<category><![CDATA[NtClose]]></category>
		<category><![CDATA[NtCreateFile]]></category>
		<category><![CDATA[NtOpenFile]]></category>
		<category><![CDATA[NtReadFile]]></category>
		<category><![CDATA[RtlDosPathNameToNtPathName_U]]></category>
		<category><![CDATA[RtlInitUnicodeString]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=115</guid>
		<description><![CDATA[Just two litle snippet: AnsiToFile: function for write ansistring value to file use native api FileToAnsi: function for read file to ansistring use native api example:<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=115&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Just two litle snippet:</p>
<blockquote><p>AnsiToFile: function for write ansistring value to file use native api<br />
FileToAnsi: function for read file to ansistring use native api</p></blockquote>
<p><span id="more-115"></span></p>
<p><pre class="brush: plain;">
function AnsiToFile(wsFileName: WideString; Buff:AnsiString):Boolean;
var
  hFile:  THANDLE;
  Oa:     TObjectAttributes;
  Us:     TUnicodeString;
  iosb:   IO_STATUS_BLOCK;
  st:     NTSTATUS;
begin
  result := false;
  RtlDosPathNameToNtPathName_U(@wsFileName[1], Us, nil, nil);
  InitializeObjectAttributes(@Oa, @Us, $40, 0, nil);

  {Create file}
  st := NtCreateFile(
    @hFile,
    FILE_WRITE_DATA or SYNCHRONIZE,
    @oa,
    @iosb,
    nil,
    0,
    FILE_SHARE_READ,
    FILE_CREATE,
    FILE_SYNCHRONOUS_IO_NONALERT,
    nil,
    0
  );
  if st &lt;&gt; STATUS_SUCCESS then exit;

  {WriteBuff}
  NtWriteFile(
    hFile,
    0,
    nil,
    nil,
    @iosb,
    @Buff[1],
    length(Buff),
    nil,
    nil
  );

  NtClose(hFile);
end;

function FileToAnsi(wsFileName: WideString):AnsiString;
var
  hFile:  THANDLE;
  Oa:     TObjectAttributes;
  Us:     TUnicodeString;
  iosb:   IO_STATUS_BLOCK;
  fsi:    FILE_STANDARD_INFORMATION;
  st:     NTSTATUS;
  fsize:  Cardinal;
begin
  result := '';
  RtlDosPathNameToNtPathName_U(@wsFileName[1], Us, nil, nil);
  InitializeObjectAttributes(@Oa, @Us, $40, 0, nil);

  {open file}
  st := NtOpenFile(
    @hFile,
    FILE_READ_DATA or SYNCHRONIZE,
    @oa,
    @iosb,
    FILE_SHARE_READ,
    FILE_SYNCHRONOUS_IO_NONALERT
  );
  if st &lt;&gt; STATUS_SUCCESS then exit;

  {Query Information File}
  st := NtQueryInformationFile(
    hFile,
    @iosb,
    @fsi,
    Sizeof(FILE_STANDARD_INFORMATION),
    FileStandardInformation//FileStandardInformation
  );
  if st &lt;&gt; STATUS_SUCCESS then begin
    NtClose(hFile);
    exit;
  end;

  {Get FileSize}
  fsize := fsi.EndOfFile.LowPart;
  Setlength(result, fsize);

  {ReadFile}
  NtReadFile(
    hFile,
    0,
    nil,
    nil,
    @iosb,
    @result[1],
    fsize,
    nil,
    nil
  );

  NtClose(hFile);

end;
</pre></p>
<p>example:<br />
<pre class="brush: plain;">
var
  buff:ansistring;
begin
  buff := FileToAnsi(paramstr(0));
  AnsiToFile('test.exe', buff);
end.
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/115/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=115&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/11/05/delphi-native-file-read-and-write-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi]PEB from WoW64 Process</title>
		<link>http://cybercoding.wordpress.com/2011/10/14/delphipeb-from-wow64-process/</link>
		<comments>http://cybercoding.wordpress.com/2011/10/14/delphipeb-from-wow64-process/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 15:44:33 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[LdrData]]></category>
		<category><![CDATA[LdrModule]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[PEB]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[SystemProcessesAndThreadsInformation]]></category>
		<category><![CDATA[WoW64]]></category>
		<category><![CDATA[ZwQuerySystemInformation]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=109</guid>
		<description><![CDATA[playing PEB (Process Environment Block) again . Now try Extract PEB information from 64bit process, use Wow64 api. about WoW64 : [url]http://en.wikipedia.org/wiki/WoW64[/url] [url]http://msdn.microsoft.com/en-us/library/aa384274(v=vs.85).aspx[/url] Instead of using the x86 system-service call sequence, 32-bit binaries that make system calls are rebuilt to use a custom calling sequence. This calling sequence is inexpensive for WOW64 to intercept because [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=109&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>playing PEB (Process Environment Block) again <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> . Now try Extract PEB information from 64bit process, use Wow64 api. </p>
<p>about WoW64 :<br />
[url]http://en.wikipedia.org/wiki/WoW64[/url]<br />
[url]http://msdn.microsoft.com/en-us/library/aa384274(v=vs.85).aspx[/url]</p>
<blockquote><p>Instead of using the x86 system-service call sequence, 32-bit binaries that make system calls are rebuilt to use a custom calling sequence. This calling sequence is inexpensive for WOW64 to intercept because it remains entirely in user mode. When the custom calling sequence is detected, the WOW64 CPU transitions back to native 64-bit mode and calls into Wow64.dll. Thunking is done in user mode to reduce the impact on the 64-bit kernel and to reduce the risk of a bug in the thunk that might cause a kernel-mode crash, data corruption, or a security hole. The thunks extract arguments from the 32-bit stack, extend them to 64 bits, then make the native system call.</p></blockquote>
<p><span id="more-109"></span></p>
<p><pre class="brush: plain;">
program Test;

uses
  windows,
  JwaNative,
  JwaNtStatus,
  JwaWinType,
  NcxTypes,
  NcxNtDef,
  NcxNtTeb;

var
  WOW32Reserved: Cardinal;

function IsWow:NativeUint; stdcall;
asm
  xor   eax, eax
  mov   eax, fs:[eax+$18] //teb
  mov   eax, [eax+$C0] //WOW32Reserved
end;

(******************************************************************************
 | Native WOW64                                                                |
 ******************************************************************************)
function  NtWow64QueryInformationProcess64(
    ProcessHandle : THANDLE;
    ProcessInformationClass : PROCESSINFOCLASS;
    ProcessInformation : Pointer;
    ProcessInformationLength : ULONG;
    ReturnLength : PUInt64
  ): NTSTATUS; stdcall; external ntdll;


function  NtWow64ReadVirtualMemory64(
    ProcessHandle : THANDLE;
    BaseAddress : UInt64;
    Buffer : Pointer;
    BufferLength : UInt64;
    ReturnLength : PUInt64
  ): NTSTATUS; stdcall; external ntdll;


 (******************************************************************************
 | Native Misc                                                                 |
 ******************************************************************************)
function NtSuccess(AStatus: LongInt): Boolean;
var
  error : DWord;
begin
  Result := AStatus &gt;= 0;
  if result=false then begin
    error := RtlNtStatusToDosError(AStatus);
    SetLastError(error);
    {$IFDEF DebugMode}Codesite.SendWinError(error);{$ENDIF}
  end;
end;

Function GetInformation(Table:SYSTEM_INFORMATION_CLASS):Pointer;
var
  mSize: dword;
  mPtr: pointer;
  St: LongInt;
begin
  result := nil;
  mSize := $4000;
  repeat
    GetMem(mPtr, mSize);
    St := NtQuerySystemInformation(Table, mPtr, mSize, nil);
    if (St = STATUS_INFO_LENGTH_MISMATCH) then begin
      FreeMem(mPtr);
      mSize := mSize * 2;
    end;
  until St &lt;&gt; STATUS_INFO_LENGTH_MISMATCH;
  if (St = STATUS_SUCCESS) then result := mPtr
  else FreeMem(mPtr);
end;

function ExOpenProcess(dwDesiredAccess: DWord; Id : DWord):THANDLE;
var
  hProcess: THANDLE;
  attr: OBJECT_ATTRIBUTES;
  cli: CLIENT_ID;
begin
  InitializeObjectAttributes(@attr, nil, 0, 0, nil);
  cli.UniqueProcess := THandle(Id);
  cli.UniqueThread := 0;
  result := 0;
  if NtSuccess(NtOpenProcess(@hProcess, dwDesiredAccess, @attr, @cli)) then result := hProcess
end;

function ExOpenThread(dwDesiredAccess: DWord; Id : DWord):THANDLE;
var
  hThread: THANDLE;
  attr: OBJECT_ATTRIBUTES;
  cli: CLIENT_ID;
begin
  InitializeObjectAttributes(@attr, nil, 0, 0, nil);
  cli.UniqueProcess := 0;
  cli.UniqueThread := THandle(Id);
  result := 0;
  if NtSuccess(NtOpenThread(@hThread, dwDesiredAccess, @attr, @cli)) then result := hThread
end;

function Is64BitProcess(ph:DWORD):Boolean;
var
  isWow64: ULONG_PTR;
begin
  result := false;
  isWow64 := 1;
  if ph=GetcurrentProcess then exit;

  try
    {Get PROCESS_BASIC_INFORMATION}
    if not NtSuccess(NtQueryInformationProcess(ph, ProcessWow64Information, @isWow64, SizeOf(isWow64), nil)) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Get ProcessWow64Information', Getlasterror);{$ENDIF}
      exit;
    end;
  finally
  end;

  if (WOW32Reserved&lt;&gt;0) then
    result := (isWow64=0)
  else
    result := (isWow64&lt;&gt;0)

end;

Type
  PROCESS_BASIC_INFORMATION = record
    ExitStatus: Cardinal;
    PebBaseAddress: PVOID;
    AffinityMask: Cardinal;
    BasePriority: Cardinal;
    UniqueProcessId: Cardinal;
    InheritedFromUniqueProcessId: Cardinal;
  end;
  TProcessBasicInformation = PROCESS_BASIC_INFORMATION;
  PProcessBasicInformation = ^TProcessBasicInformation;

  PROCESS_BASIC_INFORMATION64 = record
    ExitStatus: Cardinal;
    Pad1:Cardinal;
    PebBaseAddress: UInt64;
    AffinityMask: UInt64;
    BasePriority: Cardinal;
    Pad2:Cardinal;
    UniqueProcessId: UInt64;
    InheritedFromUniqueProcessId: UInt64;
  end;
  TProcessBasicInformation64 = PROCESS_BASIC_INFORMATION64;
  PProcessBasicInformation64 = ^TProcessBasicInformation64;

(******************************************************************************
 | PEB Misc                                                                    |
 ******************************************************************************)
function GetPeb32(ph : THandle; var PEB : TPeb32):Boolean;
var
  PBI           : PROCESS_BASIC_INFORMATION;
begin
  result := false;

  {Get PROCESS_BASIC_INFORMATION}
  if not NtSuccess(NtQueryInformationProcess(ph, ProcessBasicInformation, @PBI, SizeOf(PBI), nil)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Get PROCESS BASIC INFORMATION  ', Getlasterror);{$ENDIF}
    exit;
  end;

  {Reading PEB}
  if not NtSuccess(NtReadVirtualMemory(ph, pbi.PebBaseAddress, @PEB, sizeof(PEB), nil)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading PEB', Getlasterror);{$ENDIF}
    exit;
  end;

  result := true;
end;

function GetPeb64(ph : THandle; var PEB : TPeb64):Boolean;
var
  PBI           : PROCESS_BASIC_INFORMATION64;
begin
  result := false;

  {Get PROCESS_BASIC_INFORMATION}
  if not NtSuccess(NtWow64QueryInformationProcess64(ph, ProcessBasicInformation, @PBI, SizeOf(PBI), nil)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Get PROCESS BASIC INFORMATION  ', Getlasterror);{$ENDIF}
    exit;
  end;

  {Reading PEB}
  if not NtSuccess(NtWow64ReadVirtualMemory64(ph, pbi.PebBaseAddress, @PEB, sizeof(PEB), nil)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading PEB', Getlasterror);{$ENDIF}
    exit;
  end;

  result := true;
end;

Function PEB32ProcName(ph : THandle; Base:boolean):String;
var
  PEB           : TPeb32;
  LdrData       : TPebLdrData32;
  LdrModule     : TLdrDataTableEntry32;
  BaseDllName   : array[0..MAX_PATH] of widechar;
  dwread,
  Current       : DWORD;
begin
  result := '';
  if not GetPeb32(ph, PEB) then exit;

  Fillchar(BaseDllName, sizeof(BaseDllName), 0);

  {Reading LoaderData}
  if not NtSuccess(NtReadVirtualMemory(ph, PEB.Ldr, @LdrData, sizeof(LdrData), @dwread)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading LdrData ',Getlasterror);{$ENDIF}
    exit;
  end;

  Current := DWord(LdrData.InLoadOrderModuleList.Flink);

  {Reading First entry}
  if not NtSuccess(NtReadVirtualMemory(ph, Ptr(Current), @LdrModule, SizeOf(LdrModule), @dwread)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading Current Module ',Getlasterror); {$ENDIF}
    exit;
  end;

  if base then begin
    {Reading BaseDllName}
    if not NtSuccess(NtReadVirtualMemory(ph, LdrModule.BaseDllName.Buffer, @BaseDllName, LdrModule.BaseDllName.Length, nil)) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading BaseDllName ',Getlasterror);{$ENDIF}
      exit;
    end;
  end else begin
    {Reading FullDllName}
    if not NtSuccess(NtReadVirtualMemory(ph, LdrModule.FullDllName.Buffer, @BaseDllName, LdrModule.FullDllName.Length, nil)) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading FullDllName ',Getlasterror);{$ENDIF}
      exit;
    end;
  end;

  result := String(BaseDllName);
end;

Function PEB64ProcName(ph : THandle; Base:boolean):String;
var
  PEB           : TPeb64;
  LdrData       : TPebLdrData64;
  LdrModule     : TLdrDataTableEntry64;
  BaseDllName   : array[0..MAX_PATH] of widechar;
  dwread,
  Current:        Uint64;
begin
  result := '';
  if not GetPeb64(ph, PEB) then exit;

  Fillchar(BaseDllName, sizeof(BaseDllName), 0);

  {Reading LoaderData}
  if not NtSuccess(NtWow64ReadVirtualMemory64(ph, PEB.Ldr, @LdrData, sizeof(LdrData), @dwread)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading LdrData', Getlasterror);{$ENDIF}
    exit;
  end;

  Current := Uint64(LdrData.InLoadOrderModuleList.Flink);

  {Reading First entry}
  if not NtSuccess(NtWow64ReadVirtualMemory64(ph, Current, @LdrModule, sizeof(LdrModule), @dwread)) then begin
    {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading Current Module ',Getlasterror); {$ENDIF}
    exit;
  end;

  if base then begin
    {Reading BaseDllName}
    if not NtSuccess(NtWow64ReadVirtualMemory64(ph, NativeUint(LdrModule.BaseDllName.Buffer), @BaseDllName, LdrModule.BaseDllName.Length, nil)) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading BaseDllName ',Getlasterror);{$ENDIF}
      exit;
    end;
  end else begin
    {Reading FullDllName}
    if not NtSuccess(NtWow64ReadVirtualMemory64(ph, NativeUint(LdrModule.FullDllName.Buffer), @BaseDllName, LdrModule.FullDllName.Length, nil)) then begin
      {$IFDEF DebugMode}Codesite.SendWinError('Failed Reading FullDllName ',Getlasterror);{$ENDIF}
      exit;
    end;
  end;

  result := String(BaseDllName);
end;

type
  TProcessInfo = record
    is64 : Boolean;
    PID :Cardinal;
    ProcName,
    Filename : String;
  end;
  TProcList = array of TProcessInfo;

Function NativeEnumProcess:TProcList;
var
  buffer: Pointer;
  pInfo:  PSystemProcesses;
  ph:     THandle;
begin
  SetLength(result, 0);

  { Get WOW32Reserved for check if this x64 OS }
  WOW32Reserved := IsWow;

  { Get SystemProcessesAndThreads Information }
  buffer := GetInformation(SystemProcessesAndThreadsInformation);  //5
  if not assigned(buffer) then exit;
  pInfo := PSystemProcesses(buffer);

  try
    { Enum All Info }
    Repeat

      setlength(result, length(result)+1);
      with result[High(result)] do begin
        PID := pInfo^.ProcessId;

        { OpenProcess }
        ph := ExOpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, PID);
        if (ph&lt;&gt;0) and (ph&lt;&gt;INVALID_HANDLE_VALUE) then begin

          is64 := Is64BitProcess(ph);
          if is64 then begin
            ProcName := PEB64ProcName(ph, True);
            Filename := PEB64ProcName(ph, False);
          end else begin
            ProcName := PEB32ProcName(ph, True);
            Filename := PEB32ProcName(ph, False);
          end;

          { Close Opened Process }
          NtClose(ph);
        end;
      end;

      { Next Info }
      if pInfo^.NextEntryDelta = 0 then break;
      pInfo := pointer(dword(pInfo) + pInfo^.NextEntryDelta);
    until false;
  finally
    FreeMem(buffer);
  end;
end;


begin
  NativeEnumProcess;
end.

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/109/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=109&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/10/14/delphipeb-from-wow64-process/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] Ex &#8211; GetmoduleHandle 32-64 bit</title>
		<link>http://cybercoding.wordpress.com/2011/10/07/delphi-ex-getmodulehandle-32-64-bit/</link>
		<comments>http://cybercoding.wordpress.com/2011/10/07/delphi-ex-getmodulehandle-32-64-bit/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 13:06:53 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[BaseDllName]]></category>
		<category><![CDATA[GetLdr]]></category>
		<category><![CDATA[GetmoduleHandle]]></category>
		<category><![CDATA[InMemoryOrderModuleList]]></category>
		<category><![CDATA[Module]]></category>
		<category><![CDATA[NativeUint]]></category>
		<category><![CDATA[PEB]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=105</guid>
		<description><![CDATA[just test code a crypter in xe2 (64bit). Bcoz in 64bit peb location moved and sizeof pointer is 8, some walking peb failed and u will get error . Btw here u go alternative getmodulehandle compatible 32 and 64bit pe (xe2) [CODE] function GetLdr:Pointer; stdcall; asm {$IFDEF CPUX86} xor eax, eax mov eax, fs:[eax+$18] //teb [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=105&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>just test code a crypter in xe2 (64bit). Bcoz in 64bit peb location moved and sizeof pointer is 8, some walking peb failed and u will get error <img src='http://s0.wp.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> . </p>
<p>Btw here u go alternative getmodulehandle compatible 32 and 64bit pe (xe2)<br />
<span id="more-105"></span></p>
<p>[CODE]<br />
function GetLdr:Pointer; stdcall;<br />
asm<br />
{$IFDEF CPUX86}<br />
  xor   eax, eax<br />
  mov   eax, fs:[eax+$18] //teb<br />
  mov   eax, [eax+$30] //peb<br />
  mov   eax, [eax+$0C] //ldr<br />
{$ELSE}<br />
  xor   rax, rax<br />
  mov   rax, gs:[rax+$30] //teb<br />
  mov   rax, [rax+$60] //peb<br />
  mov   rax, [rax+$18] //ldr<br />
{$ENDIF}<br />
end;</p>
<p>function ExGetmoduleHandle(name: PWideChar): THANDLE;<br />
var<br />
  x, f, cur  : NativeUint;<br />
begin<br />
  result := 0;<br />
  //getLdr<br />
  x := NativeUint(GetLdr);<br />
{$IFDEF CPUX86}<br />
  //InMemoryOrderModuleList<br />
  f := x+$14;<br />
  //InMemoryOrderModuleList.Flink<br />
  cur := PNativeUint(f)^;<br />
  while (cur  f) do begin<br />
    x := cur &#8211; $8;<br />
    //BaseDllName<br />
    if (StrComp(PWideChar(PNativeUint(x+$30)^), name) = 0) then begin<br />
      //DllBase<br />
      result := PNativeUint(x+$18)^;<br />
      exit;<br />
    end;<br />
    cur := PNativeUint(cur)^;<br />
  end;<br />
{$ELSE}<br />
  //InMemoryOrderModuleList<br />
  f := x+$20;<br />
  //InMemoryOrderModuleList.Flink<br />
  cur := PNativeUint(f)^;<br />
  while (cur  f) do begin<br />
    x := cur &#8211; $10;<br />
    //BaseDllName<br />
    if (StrComp(PWideChar(PNativeUint(x+$60)^), name) = 0) then begin<br />
      //DllBase<br />
      result := PNativeUint(x+$30)^;<br />
      exit;<br />
    end;<br />
    cur := PNativeUint(cur)^;<br />
  end;<br />
{$ENDIF}<br />
end;<br />
[/CODE]</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/105/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=105&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/10/07/delphi-ex-getmodulehandle-32-64-bit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] GetProcAddress x32-x64</title>
		<link>http://cybercoding.wordpress.com/2011/10/03/delphi-getprocaddress-x32-x64/</link>
		<comments>http://cybercoding.wordpress.com/2011/10/03/delphi-getprocaddress-x32-x64/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 01:18:04 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Portable Executable]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Alternative GetProcAddress]]></category>
		<category><![CDATA[Export Directory]]></category>
		<category><![CDATA[GetProcAddress 32-64]]></category>
		<category><![CDATA[PE File]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=102</guid>
		<description><![CDATA[Lagi test2 xe2 delphi yang mana sudah mendukung compile 64bit.. btw sekalian share nih alternative getprocaddress, support 32 and 64bit pe. (method walking the export directory table for function address)<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=102&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lagi test2 xe2 delphi yang mana sudah mendukung compile 64bit.. btw sekalian share nih alternative getprocaddress, support 32 and 64bit pe.</p>
<p>(method walking the export directory table for function address)</p>
<p><pre class="brush: plain;">
type
  PUInt32 = ^UInt32;
  UInt32 = LongWord;
  PUInt64 = ^UInt64;
  UInt64 = System.UInt64;

  PSizeT = ^TSizeT;
  TSizeT = {$IFDEF CPUX64} UInt64 {$ELSE} UInt32 {$ENDIF};

const
  // PE header constants
  IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b;  // 32bit PE file
  IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20b;  // 64bit PE file

Function xGetProcAddress(Module: TSizeT; ProcName: String):Pointer;
var
  pIDH: PImageDosHeader absolute Module;
  pINH : PImageNtHeaders32;
  pIDD: PImageDataDirectory;
  pIED: PImageExportDirectory;
  pdwFuncs1,
  pdwFuncs,
  pdwNames: PULONG;
  pdwOrdinals: PWORD;
  dwOrd1, i, k: cardinal;
  apiname:PAnsiChar;
begin
  result := nil;
  if (Module=0) then exit;

  if (pIDH^.e_magic &lt;&gt; IMAGE_DOS_SIGNATURE) then exit;
  pINH := Pointer(Pbyte(pIDH) + pIDH^._lfanew);
  if (pINH^.Signature &lt;&gt; IMAGE_NT_SIGNATURE) then exit;

  if pINH^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
    pIDD := @PImageOptionalHeader64(@pINH^.OptionalHeader).DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
  else
    pIDD := @pINH^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];

  pIED := Pointer(Pbyte(pIDH) + pIDD^.VirtualAddress);
  if (pIED=nil) then exit;

  pdwFuncs := PULONG(Pbyte(pIDH) + Cardinal(pIED^.AddressOfFunctions));
  pdwNames := PULONG(Pbyte(pIDH) + Cardinal(pIED^.AddressOfNames));
  pdwOrdinals := PWORD(Pbyte(pIDH) + Cardinal(pIED^.AddressOfNameOrdinals));
  pdwFuncs1 := pdwFuncs;
  for I := 0 to pIED^.NumberOfFunctions do begin

    dwOrd1 := pdwOrdinals^;
    k := 0;
    pdwFuncs := pdwFuncs1;
    while (k &lt; dwOrd1) do begin
      inc(pdwFuncs);
      inc(k);
    end;

    if (pdwFuncs^ &lt; pIDD^.VirtualAddress) or (pdwFuncs^ &gt;= pIDD^.VirtualAddress + pIDD^.Size) then begin
      apiname := PAnsiChar(Pbyte(pIDH) + pdwNames^);
      if (AnsiStrComp(apiname, Pansichar(AnsiString(ProcName))) = 0) then begin
        result := Pointer(Pbyte(pIDH) + pdwFuncs^);
        exit;
      end;
    end;

    inc(pdwOrdinals);
    inc(pdwNames);
  end;
end;</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/102/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/102/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/102/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/102/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/102/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/102/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/102/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/102/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=102&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/10/03/delphi-getprocaddress-x32-x64/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
		<item>
		<title>[Delphi] VirtualMemory Implementasion</title>
		<link>http://cybercoding.wordpress.com/2011/09/20/delphi-virtualmemory-implementasion/</link>
		<comments>http://cybercoding.wordpress.com/2011/09/20/delphi-virtualmemory-implementasion/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 07:08:05 +0000</pubDate>
		<dc:creator>cybercoding</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Code Virtualization]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Virtual Machine]]></category>
		<category><![CDATA[Virtualization]]></category>
		<category><![CDATA[VirtualMemory]]></category>
		<category><![CDATA[VM]]></category>
		<category><![CDATA[VMem]]></category>

		<guid isPermaLink="false">http://cybercoding.wordpress.com/?p=89</guid>
		<description><![CDATA[Implementasi VirtualMemory buat digunain untuk Emulator / VM (Virtual Machine) anda. jelasnya tentang virtualMemory baca di http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/ Windows on 32 bit x86 systems can access up to 4GB of physical memory. This is due to the fact that the processor’s address bus which is 32 lines or 32 bits can only access address range from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=89&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Implementasi VirtualMemory buat digunain untuk Emulator / VM (Virtual Machine) anda. </p>
<p>jelasnya tentang virtualMemory baca di<br />
<code>http://www.rohitab.com/discuss/topic/31139-tutorial-paging-memory-mapping-with-a-recursive-page-directory/</code></p>
<blockquote><p>Windows on 32 bit x86 systems can access up to 4GB of physical memory. This is due to the fact<br />
that the processor’s address bus which is 32 lines or 32 bits can only access address range from<br />
0&#215;00000000 to 0xFFFFFFFF which is 4GB. Windows also allows each process to have its own<br />
4GB logical address space. The lower 2GB of this address space is available for the user mode<br />
process and upper 2GB is reserved for Windows Kernel mode code. How does Windows give 4GB<br />
address space each to multiple processes when the total memory it can access is also limited to<br />
4GB. To achieve this Windows uses a feature of x86 processor (386 and above) known as paging.<br />
Paging allows the software to use a different memory address (known as logical address) than the<br />
physical memory address. The Processor’s paging unit translates this logical address to the physical<br />
address transparently. This allows every process in the system to have its own 4GB logical address<br />
space. </p></blockquote>
<p><span id="more-89"></span><br />
here u go the code</p>
<p><pre class="brush: plain;">
{ U_VMemory
Author: Abhe
Description: VirtualMemory Implementasion (ported from Libemu)
Release Date: 20th September 2011
Website: http://cybercoding.wordpress.com/
}
unit U_VMemory;

interface
{$I Build.inc}
uses
Windows, U_VUtils, U_VLog, TypInfo;

type
  PArrayPointer = ^TArrayPointer;
  TArrayPointer = Array [0..1023] of Pointer;
  TSegment = (s_cs, s_ss, s_ds, s_es, s_fs, s_gs);

  TMemRange = record
    id: Char;
    start, Stop : Cardinal;
  end;

  TVMemory = class
  Private
    {Physical Directory Table}
    PDT: Pointer;

    {SegMent}
    ST: Array [TSegment] of DWORD;
    SO: DWORD;
    SC: TSegment;

    MemPoints: Array of DWORD;
    MemRangess: Array of TMemRange;

    Procedure MemoryCheck(addr, len: DWORD; mode:char);
    Function PageAlloc(addr:DWORD):Boolean;
    Function PageDealloc(addr:DWORD):Boolean;
    Procedure Clear;
    Function PageIsAlloc(addr: DWORD):Boolean;
    Function Translate(addr: DWORD):Integer;
  Public
    OnMemPoints: Procedure (addr: DWORD);
    OnMemRangess: Procedure (id, mode: char; addr: DWORD);

    constructor Create;
    Destructor Destroy; override;

    function AllocMemory(var addr: DWORD; Size:DWORD):boolean;
    Procedure DeallocMemory(addr: DWORD; Size:DWORD);

    Function ReadBlock(addr: DWORD; Size:DWORD; dest:Pointer):Integer;
    Function WriteBlock(addr:DWORD; Write:Pointer; Size:DWORD):integer;

    Procedure SelectSegment(s: TSegment);
    Function GetSegMent: TSegment;

    Procedure AddMonitorPoint(addr: DWORD);
    Procedure AddMonitorRange(id:Char; start,Stop: DWORD);
    Procedure ClearMonitorPoint;
    Procedure ClearMonitorRange;
  end;


{$IFDEF VirtualMemory} var  VMemory : TVMemory; {$ENDIF}

type
  TMem = Record
    class function Read&lt;T&gt;(addr:DWORD): T; static;
    class function Write&lt;T&gt;(addr:DWORD; Data:T): Integer; static;
    class function Alloc(var addr:DWORD; Size:DWORD): boolean; static;
    class Procedure Dealloc(addr:DWORD; Size:DWORD); static;
    class Function ReadBlock(addr: DWORD; dest:Pointer; Size:Dword):Integer; static;
    class Function WriteBlock(addr:DWORD; Write:Pointer; Size:DWord):integer; static;
  end;

const
  PAGE_BITS = 12;
  PAGESET_BITS = 10;
  PAGE_SIZE = (1 shl PAGE_BITS);
  PAGESET_SIZE = (1 shl PAGESET_BITS);
  FS_SEGMENT_DEFAULT_OFFSET = $7ffdf000;

implementation

class Function TMem.ReadBlock(addr: DWORD; dest:Pointer; Size:DWORD):Integer;
begin
{$IFDEF VirtualMemory}
  result := VMemory.ReadBlock(addr, Size, dest);
{$ELSE}
  if (Pointer(addr)=nil) then Log('Read UnAllocated Memory %x', lgError, [addr]);
  CopyMemory(dest, Pointer(addr), Size);
  result := Size;
{$ENDIF}
end;

class Function TMem.WriteBlock(addr:DWORD; Write:Pointer; Size:DWORD):integer;
begin
{$IFDEF VirtualMemory}
  result := VMemory.WriteBlock(addr, Write, Size);
{$ELSE}
  if (Pointer(addr)=nil) then Log('Write UnAllocated Memory %x', lgError, [addr]);
  CopyMemory(Pointer(addr), Write, Size);
{$ENDIF}
end;

class function TMem.Read&lt;T&gt;(addr:DWORD): T;
var
  ti: PTypeInfo;
  ds: integer;
  Size:Integer;
begin
  ti := System.TypeInfo(T);
  if assigned(ti) then begin
    ds := GetInlineSize(ti);
    TMem.ReadBlock(addr, @result, ds);
  end;
end;

class function TMem.Write&lt;T&gt;(addr:DWORD; Data:T): Integer;
var
  ti: PTypeInfo;
  ds: integer;
  dt: Pointer;
begin
  result := -1;
  ti := System.TypeInfo(T);
  if assigned(ti) then begin
    ds := GetInlineSize(ti);
    result := TMem.WriteBlock(addr, @Data, ds);
  end;
end;

class function TMem.Alloc(var addr:DWORD; Size:DWORD): boolean;
begin
{$IFDEF VirtualMemory}
  result := VMemory.AllocMemory(Addr, Size);
{$ELSE}
  addr := Cardinal(AllocMem(Size));
  result := true;
{$ENDIF}
end;

class Procedure TMem.Dealloc(addr:DWORD; Size:DWORD);
begin
{$IFDEF VirtualMemory}
  VMemory.DeallocMemory(Addr, Size);
{$ELSE}
  FreeMem(Pointer(addr), Size);
{$ENDIF}
end;

function PAGESET(x: DWORD): DWORD;
begin
  result := ((x) shr (PAGESET_BITS + PAGE_BITS));
end;

function PAGE(x: DWORD): DWORD;
begin
  result := (((x) shr PAGE_BITS) and ((1 shl PAGESET_BITS) - 1));
end;

function OFFSET(x: DWORD): DWORD;
begin
  result := (((1 shl PAGE_BITS) - 1) and (x));
end;

constructor TVMemory.Create;
begin
  inherited create;
  PDT := AllocMem((1 shl (32 - PAGE_BITS - PAGESET_BITS))*4);
  ST[s_fs] := FS_SEGMENT_DEFAULT_OFFSET;
  SO := 0;
end;

Destructor TVMemory.Destroy;
begin
  Clear;
  inherited Destroy;
end;

Procedure TVMemory.Clear;
var
  i,j: DWORD;
  PT: Pointer;
  PG: Pointer;
begin
  if (PDT=nil) then exit;

  for i := 0 to (1 shl (32 - PAGE_BITS - PAGESET_BITS)) -1 do begin

    {Page Directory Traversal}
    if PInteger(DWORD(PDT)+i*4)^=0 then continue;
    PT := Pointer(PInteger(DWORD(PDT)+i*4)^);
    if (PT=nil) then begin
      Log('Allocated But Nil [Table: %d = %x]', lgerror, [i, DWORD(PT)]);
      continue;
    end;

    {Page Table Traversal}
    for j := 0 to PAGESET_SIZE -1 do begin
      if PInteger(DWORD(PT)+j*4)^=0 then continue;
      PG := Pointer(PInteger(DWORD(PT)+j*4)^);
      if (PG=nil) then begin
        Log('Allocated But Nil [Page: %d = %x]', lgerror, [i, DWORD(PG)]);
        continue;
      end;
      Freemem(PG, PAGE_SIZE);
    end;

    Freemem(PT, PAGESET_SIZE*4);
  end;
  Freemem(PDT, (1 shl (32 - PAGE_BITS - PAGESET_BITS))*4);
end;

Function TVMemory.PageAlloc(addr:DWORD):Boolean;
var
  PT:Pointer;
  PG:Pointer;
begin
  result := false;

  {Alloc PageTables}
  if PInteger(DWORD(PDT)+PAGESET(addr)*4)^=0 then begin
    PT := AllocMem(PAGESET_SIZE*4);
    PInteger(DWORD(PDT)+PAGESET(addr)*4)^ := DWORD(PT);
  end;

  {Alloc Page}
  PT := Pointer(PInteger(DWORD(PDT)+PAGESET(addr)*4)^);
  if PInteger(DWORD(PT)+PAGE(addr)*4)^=0 then begin
    PG := AllocMem(PAGE_SIZE);
    PInteger(DWORD(PT)+PAGE(addr)*4)^ := DWORD(PG);
    result := true;
  end;
end;

Function TVMemory.PageIsAlloc(addr: DWORD):Boolean;
var
  PT:Pointer;
begin
  result := false;
  if PInteger(DWORD(PDT)+PAGESET(addr)*4)^=0 then exit;
  PT := Pointer(PInteger(DWORD(PDT)+PAGESET(addr)*4)^);
  if (PT=nil) then exit;
  result := PInteger(DWORD(PT)+PAGE(addr)*4)^ &lt;&gt; 0;
end;

Function TVMemory.Translate(addr: DWORD):Integer;
var
  PT:Pointer;
  base:DWORD;
begin
  result := 0;
  if PInteger(DWORD(PDT)+PAGESET(addr)*4)^=0 then exit;
  PT := Pointer(PInteger(DWORD(PDT)+PAGESET(addr)*4)^);
  if (PT=nil) then exit;
  base := PInteger(DWORD(PT)+PAGE(addr)*4)^;
  result := base+OFFSET(addr);
end;

Function TVMemory.PageDealloc(addr:DWORD):Boolean;
var
  PT:Pointer;
  PG: Pointer;
begin
  result := false;
  if PInteger(DWORD(PDT)+PAGESET(addr)*4)^=0 then exit;
  PT := Pointer(PInteger(DWORD(PDT)+PAGESET(addr)*4)^);
  if (PT=nil) then exit;
  PG := Pointer(PInteger(DWORD(PT)+PAGE(addr)*4)^);
  FreeMem(PG, PAGE_SIZE);
  PInteger(DWORD(PT)+PAGE(addr)*4)^ := 0;
  result := true;
end;

Procedure TVMemory.DeallocMemory(addr: DWORD; Size:DWORD);
var
  i, pages : Cardinal;
begin
  if Size=0 then exit;
  pages := Size div PAGE_SIZE;
  if( Size mod PAGE_SIZE &lt;&gt; 0 ) then inc(pages);
  for i:=0 to pages -1 do PageDealloc(addr + i * PAGE_SIZE);
end;

function TVMemory.AllocMemory(var addr: DWORD; Size:DWORD): Boolean;
var
  i, pages : DWORD;
begin
  result := false;
  if Size=0 then exit;
  addr := $00200000;
  pages := Size div PAGE_SIZE;
  if( Size mod PAGE_SIZE &lt;&gt; 0 ) then inc(pages);
  while 1=1 do begin
    for i:=0 to pages -1 do begin
      if not PageIsAlloc(addr + i * PAGE_SIZE) then break;
    end;
    if i=pages-1 then begin
      for i:=0 to pages -1 do begin
        if not PageAlloc(addr + i * PAGE_SIZE) then exit;
      end;
      result := true;
      exit;
    end;
    addr := addr +  PAGE_SIZE;
  end;
end;

Function TVMemory.ReadBlock(addr: DWORD; Size:DWORD; dest:Pointer): integer;
var
  address: DWORD;
  oaddr: DWORD;
  cb: DWORD;
begin
  result := -1;

  oaddr := addr;
  addr := addr + SO;
  MemoryCheck(addr, Size, 'r');
  address := translate(addr);
  if ( address = 0 ) and (Pointer(address) = nil) then begin
    Log('accessing %x', lgError, [addr]);
    exit;
  end;

  if (OFFSET(addr) + Size &lt;= PAGE_SIZE) then begin
    CopyMemory(dest, Pointer(address), Size);
    result := Size;
  end else begin
    cb := PAGE_SIZE - OFFSET(addr);
    CopyMemory(dest, Pointer(address), cb);
    result := result + readblock(oaddr + cb, Size - cb, Pointer(DWord(dest)+cb));
  end;
end;

Function TVMemory.WriteBlock(addr:DWORD; Write:Pointer; Size:DWORD):integer;
var
  address: DWORD;
  oaddr: DWORD;
  cb: DWORD;
begin
  result := -1;

  oaddr := addr;
  addr := addr + SO;
  MemoryCheck(addr, Size, 'w');

  if( addr &lt; $1000 ) then begin
    Log('accessing %x', lgError, [addr]);
    exit;
  end;

  address := translate(addr);
  if ( address = 0 ) and (Pointer(address) = nil) then begin
    if not PageAlloc(addr) then exit;
    address := translate(addr);
  end;

  if (OFFSET(addr) + size &lt;= PAGE_SIZE) then begin
    copymemory(Pointer(address), Write, Size);
    result := Size;
  end else begin
    cb := PAGE_SIZE - OFFSET(addr);;
    copymemory(Pointer(address), Write, Size);
    result := result + WriteBlock(oaddr + cb, Pointer(DWORD(Write)+cb),size - cb);
  end;
end;

Procedure TVMemory.SelectSegment(s: TSegment);
begin
  SC := s;
  SO := ST[s];
end;

Function TVMemory.GetSegMent: TSegment;
begin
  result := SC;
end;

Procedure TVMemory.MemoryCheck(addr, len: DWORD; mode:char);
var
  i: DWORD;
begin
  if (@OnMemPoints&lt;&gt;nil) then begin
    for i:=0 to length(MemPoints)-1 do begin
      if( (MemPoints[i] &gt;= addr) and (MemPoints[i] &lt;= (addr + len) )) then
        OnMemPoints(addr);
    end;
  end;

  if (@OnMemRangess&lt;&gt;nil) then begin
    for i:=0 to length(MemRangess)-1 do begin
      if( (addr &gt;= MemRangess[i].start) and (addr &lt;= MemRangess[i].stop )) then begin
        OnMemRangess(MemRangess[i].id, mode,  addr);
        break;
      end;

      if (addr &lt; MemRangess[i].start) and ( (addr + len) &gt;= MemRangess[i].start) then begin
        OnMemRangess(MemRangess[i].id, mode,  addr);
        break;
      end;
    end;
  end;
end;

procedure TVMemory.AddMonitorPoint(addr: DWORD);
begin
  setlength(MemPoints, length(MemPoints)+1);
  MemPoints[length(MemPoints)-1] := addr;
end;

Procedure TVMemory.AddMonitorRange(id:Char; start,Stop: DWORD);
begin
  setlength(MemRangess, length(MemRangess)+1);
  MemRangess[length(MemRangess)-1].id := id;
  MemRangess[length(MemRangess)-1].start := start;
  MemRangess[length(MemRangess)-1].Stop := Stop;
end;

Procedure TVMemory.ClearMonitorPoint;
begin
   setlength(MemPoints, 0);
end;

Procedure TVMemory.ClearMonitorRange;
begin
  setlength(MemRangess, 0);
end;


{$IFDEF VirtualMemory}
initialization
  VMemory := TVMemory.Create;

finalization
  VMemory.Free;

{$ENDIF}


end.
</pre></p>
<p>sample</p>
<p><pre class="brush: plain;">var
  x: Cardinal;
begin
  TMem.Alloc(x, 1);
  TMem.Write&lt;BYTE&gt;(x, $4);
  codesite.Send('x', TMem.Read&lt;Byte&gt;(x));
end.</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cybercoding.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/cybercoding.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/cybercoding.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/cybercoding.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/cybercoding.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/cybercoding.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/cybercoding.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/cybercoding.wordpress.com/89/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cybercoding.wordpress.com&amp;blog=19883806&amp;post=89&amp;subd=cybercoding&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cybercoding.wordpress.com/2011/09/20/delphi-virtualmemory-implementasion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b3431e963081b22b52c768fece026052?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cybercoding</media:title>
		</media:content>
	</item>
	</channel>
</rss>
