Answer
stringlengths
38
29k
Id
stringlengths
1
5
CreationDate
stringlengths
23
23
Body
stringlengths
55
28.6k
Title
stringlengths
15
145
Tags
stringlengths
3
68
<p>I've found <a href="http://pid.gamecopyworld.com/" rel="nofollow">Protection ID</a> to be fast and comprehensive (last update in late 2013).</p>
4339
2014-05-15T13:30:21.923
<p>What are some good programs that can detect which protection software has been used on or in other programs and their libraries?</p>
What program can I use to detect protections used on a program and its libraries?
|anti-debugging|packers|copy-protection|protection|
<p>You can write script for ODbgScript plugin,</p> <p>It might look like this: </p> <pre><code>VAR pDest VAR Val mov pDest, FB2D0024 // dest address mov Val, E9 // val to look for bpwm pDest, 4 // set bp on writing DWORD (4bytes) value. __lbl_loop: erun cmp [pDest], Val jne __lbl_loop bpmc LOG "Catched ^(._.^)" </code></pre>
4345
2014-05-16T05:52:00.173
<p>I'm wanting to have olly run a program and break when a particular memory location equals a given value. For instance, if I could have it run until the value at address 0xFB2D0024 == 0xE9, and then break immediately when that assignment occurs. Please let me know if this is possible!</p> <p>The "conditional" breaks I found in <a href="https://reverseengineering.stackexchange.com/questions/2763/how-to-set-a-conditional-breakpoint-on-specific-register-value-in-ollydbg">here</a> did not work, or rather when I right clicked -> breakpoint -> Conditional, and then entered a condition, the program simply broke at the instruction where I right-clicked, regardless of the condition, and not when the condition occurred.</p> <p>The closest I can get is right clicking on a particular memory value (in the memory dump) -> breakpoint -> Memory, on write, but this breaks every time a change is made, and not when a specific value is set. Any help would be great! Thanks!</p>
OllyDbg Break when memory equals value
|ollydbg|
<p>The catch is to determine whether the image in question uses a "standard" C runtime library of sorts (glibc, musl, uclibc) or not. If it does, then you can grab the entry point address and match the code at that address against your collection of startup routines from those libraries and pinpoint the main() location as you'd know which <code>call</code> is the one transferring control to <code>main()</code>.</p> <p>Then, the image might not be linked against any well-known C runtime, say, if it's a code piece that directly invokes kernel syscalls or if it managed to whip its own CRT library.</p> <p>Another good point would be if the program wasn't written in C at all and uses some other fancy language, but that seems to be outside the scope of the question as <code>main()</code> won't be relevant for those, I guess.</p>
4349
2014-05-16T16:55:14.417
<p>So basically I am working on some tripped <em>dynamic linked</em> ELF binaries (32 bit Linux x86), using <code>objdump</code> to disassemble them, modifying and trying to reassemble them.</p> <p>In the unstripped binary, we can get the beginning address of main function based on the symbol table, however, on the stripped binary, we just don't know where the main function is.</p> <p>Of course I can just adjust the whole <em>text</em> section, and starting from the original entry point of the ELF.</p> <p>But the problems are:</p> <ol> <li><p>There is some control transfer from the prologue/epilog of this ELF (such as <code>_start</code>; <code>__do_global_dtors_aux</code>; <code>__libc_csu_fini</code>; <code>__i686.get_pc_thunk.bx</code>; <code>__do_global_ctors_aux</code>) into the <code>.dtors</code>,<code>.ctors</code>section, which means I have to also disassemble this section.</p></li> <li><p>I am afraid that if I start from entry point in the re-assembled ELF, then I would probably <strong>double-init</strong> some stuff, because in my re-assembled asm code, I have the code of <code>_start</code>; <code>__do_global_dtors_aux</code>; <code>__libc_csu_fini</code> while linker will also attach these functions in the new ELF.</p></li> </ol> <p>So I would like to use some way to identify the <code>main</code> function in a stripped ELF (heuristically)...</p> <p>Right now I don't have some strategies on this issue, Could anyone give me some help?</p>
Is it possible to (heuristic) identify the begin addr of main function in a stripped ELF?
|disassembly|x86|elf|reassembly|
<p>You can compile your file with <a href="http://dwarfstd.org/" rel="nofollow">DWARF</a> information in it, since IDA supports it:</p> <p><img src="https://www.hex-rays.com/products/ida/6.4/shots/dwarf_x86.png" alt="DWARF in IDA"></p>
4353
2014-05-17T01:37:44.007
<p>I'm wondering if there's a way to compare source code to the disassembled assembly in IDA Pro? (e.g. I compile hello.c in Linux then open the binary in IDA Pro in OS X, and would like to compare the assembly with the source so make it easier to find out what's going on). Does such a feature exist?</p> <p><strong>ADDED From Comment:</strong> By the way, I forgot to mention, I am in OS-X and the binary was compiled by Lunux</p>
How do you compare C source code with the corresponding binary's assembly in IDA Pro?
|ida|disassembly|assembly|c|disassemblers|
<p>To answer properly your question, yes. <code>xmm</code> registers were introduced by Intel with the <code>SSE</code> instruction set (IS) in 1999 with the Pentium III CPU. <code>SSE</code> stands for Streaming SIMD Extension and is a set of vector instructions. <code>xmm</code> registers are 128bit wide and can hold 4 <code>floats</code>, 2 <code>doubles</code>, or 16 <code>chars</code>. <code>SSE</code> can speed up signal processing applications (image processing, sound processing, compression, ...), encryption, and others quite dramatically when used properly. </p> <p>On the other hand, <code>mm</code> registers are part of the <code>MMX</code> IS, another vector instruction set older than <code>SSE</code> (1997 I suppose), and are 64bit wide. Nowadays the vector instruction sets are becoming quite a <em>fashion</em> in a certain way (vector <code>CPUs</code> were the standard for supercomputers back in the 70s &amp; 80s - Cray's, ThinkingMachine's, ... computer were all vector based). In the past few years, Intel came up with many versions of <code>SSE</code> and two new IS called <code>AVX</code> &amp; <code>AVX2</code> (Advanced Vector Extension) with 256bit wide vectors implemented on SandyBridge/IvyBridge/Haswell, and <code>AVX-512</code> first implemented on the KNC (Knight's Corner) of the Xeon Phi processor &amp; co-processor line.</p> <p>I encourage you to check the Intel documentation &amp; Wikipedia for more information. </p>
4362
2014-05-18T02:57:17.370
<p>How can I view the <code>XMM0</code>-<code>XMM7</code> registers within OllyDbg? I can right click on the registers window and go to <code>view MMX</code> registers, but I'm not exactly sure that these are the same. I see an instruction: <code>MOVSS DWORD PTR DS:[ESI+8],XMM0</code> and as step through that instruction, the value shown in <code>MM0</code> on the register window does not become the value stored at <code>[ESI+8]</code>.</p> <p>So, I suppose another question is: <em>Are the <code>XMM0</code> and <code>MM0</code> registers different?</em></p>
OllyDbg and XMM0 vs MM0 registers
|ollydbg|
<p>In your case because <em>int</em> is 4 bytes and you want 20 element</p> <pre><code>int a[20] // --&gt; 20 * 4 = 0x50 </code></pre> <p>so it is very normal for <em>i</em> and <em>i_2</em></p> <p>The other thing is that your compiler didn't push <em>printf</em> arguments into stack. It pre-allocated the stack location in </p> <pre><code>var_70 = dword ptr -70h var_6C = dword ptr -6Ch var_68 = dword ptr -68h </code></pre> <p>and called the function like this</p> <pre><code>mov edx, [esp+eax*4+70h+i_2] mov eax, offset aADD ; "a[%d]=%d\n" mov [esp+70h+var_68], edx mov edx, [esp+70h+i] mov [esp+70h+var_6C], edx mov [esp+70h+var_70], eax call _printf </code></pre> <p>But there is 2 reason for such a thing (not your case)...</p> <ol> <li><p>The Compiler align the buffer for performance reasons and ease of cache. in addition unaligned buffers cause failure in some cases like Windows API calls and make debugging hard, so the compilers align every buffer to avoid this kind of failure.</p></li> <li><p>Some safe compilation allocate random number after buffers to prevent successful exploitation of buffer overruns. for example:</p> <p>and esp, 0FFFFFFF0h</p></li> </ol> <hr> <p>yeap! as @DCoder commented, you asked it <a href="https://reverseengineering.stackexchange.com/questions/4250/why-addresses-of-variable-on-stack-are-not-consecutive">Here</a> before.</p>
4363
2014-05-18T03:42:50.823
<p>Here is a sample function reverse engineered from an easy program:</p> <pre><code>main proc near var_70 = dword ptr -70h var_6C = dword ptr -6Ch var_68 = dword ptr -68h i_2 = dword ptr -54h i = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 70h mov [esp+70h+i], 0 jmp short loc_804840A loc_80483F7: mov eax, [esp+70h+i] mov edx, [esp+70h+i] add edx, edx mov [esp+eax*4+70h+i_2], edx add [esp+70h+i], 1 loc_804840A: cmp [esp+70h+i], 13h jle short loc_80483F7 mov [esp+70h+i], 0 jmp short loc_8048441 loc_804841B: mov eax, [esp+70h+i] mov edx, [esp+eax*4+70h+i_2] mov eax, offset aADD ; "a[%d]=%d\n" mov [esp+70h+var_68], edx mov edx, [esp+70h+i] mov [esp+70h+var_6C], edx mov [esp+70h+var_70], eax call _printf add [esp+70h+i], 1 loc_8048441: cmp [esp+70h+i], 13h jle short loc_804841B mov eax, 0 leave retn main endp C code #include &lt;stdio.h&gt; int main() { int a[20]; int i; for (i=0; i&lt;20; i++) a[i]=i*2; for (i=0; i&lt;20; i++) printf ("a[%d]=%d\n", i, a[i]); return 0; } </code></pre> <p>My questions are:</p> <ol> <li><p>Why is memory not allocated consecutively and why are some parts of the memory in between <code>esp + 70h -54h</code> and <code>esp + 70h -68h</code> not used?</p></li> <li><p>In <code>sub esp, 70h</code>, the number <code>70h</code> seems to be a random number in a different program, and it is often larger than we need. Why don't the compiler just allocate what we need?</p></li> </ol>
Memory allocation on the stack
|assembly|memory|stack-variables|
<p><code>ollydbg 1.10</code> right click <code>Search For All Sequences wildcard</code> <strong>MOV R32 , CONST</strong></p> <p>result from calc.exe xp sp3 32 bit vm</p> <pre><code>Found sequences Address Disassembly Comment 01001004 &lt;&amp;ADVAPI32.RegQu DD ADVAPI32.RegQueryValueExA (Initial CPU selection) 010019E5 MOV EDI, OFFSET calc.ghnoParNum 01014C08=OFFSET calc.ghnoParNum 010019EF MOV EDI, OFFSET calc.ghnoPrecNum 01014C70=OFFSET calc.ghnoPrecNum 01001A6B MOV EBX, calc.010012A0 UNICODE "intl" 01001D51 MOV ESI, 130 01001DDF MOV EAX, OFFSET calc.szBlank 01014DA4=OFFSET calc.szBlank 01001DE6 MOV EAX, calc.01001264 UNICODE " M" 01001F51 calc.WinMain MOV EAX, calc.010128EE 10128EE=calc.010128EE 01001FED MOV ESI, 400 010020A2 MOV EAX, calc.010020A8 010020A8=calc.010020A8 010020D5 MOV EAX, 80000000 0100210A MOV EDI, OFFSET calc.szAppName UNICODE "SciCalc" </code></pre> <p>combined wild card </p> <p><strong>MOV WORD PTR [R32+CONST] , R16</strong></p> <pre><code>Found sequences Address Disassembly Comment 01001F6E MOV WORD PTR SS:[EBP-FC], BX 01002234 MOV WORD PTR DS:[EAX+EDX*2+14], DI 0100230D MOV WORD PTR DS:[ESI+EAX*2+14], DI 0100231C MOV WORD PTR DS:[ESI+EAX*2+A4], DI 01002358 MOV WORD PTR SS:[EBP+EDI*2-108], AX 01002376 MOV WORD PTR SS:[EBP+EDI*2-108], AX 01002470 MOV WORD PTR DS:[ECX+EAX*2+C], BX 010024AF MOV WORD PTR DS:[ECX+ESI*2+C], BX 0100251D MOV WORD PTR DS:[EAX+ECX*2+14], DX 010025AA MOV WORD PTR DS:[ECX+EAX*2+14], DX 0100404D MOV WORD PTR SS:[EBP+EAX*2-74], BX 010056E0 MOV WORD PTR SS:[EBP+8], AX 010056F4 MOV WORD PTR SS:[EBP+A], BX 01012475 calc PUSH 70 (Initial CPU selection) </code></pre> <p><strong>edit to address comment</strong></p> <p>you <code>dont need the WORD ptr</code> simply doing<br> <strong>mov [R32+CONST] ,R16</strong><br> will fetch the same results<br> ollydbg <code>implicitly knows R!6 means word ptr</code> instead of R16<br> if you provide <code>r32</code> ollydbg will decode it as <code>DWORD PTR</code></p> <pre><code>Found sequences, item 1 Address=010017E7 Disassembly=MOV DWORD PTR SS:[EBP-2C], ESI </code></pre> <p>provide <code>mov [CONST} , R8</code> and you get back <code>all BYTE PTR</code> Sequences</p> <pre><code>Found sequences, item 1 Address=0100AC75 Disassembly=MOV BYTE PTR DS:[ftrueinfinite], BL </code></pre>
4377
2014-05-19T18:56:12.923
<p>Lets say I want to find all the</p> <pre><code>MOV EAX, 1234h MOV WORD PTR[EBP+ADDR], AX </code></pre> <p>But it won't be always <code>EAX</code> or <code>EBP+ADDR</code></p> <p>How do I wildcard search like</p> <pre><code>MOV ???, 1234h MOV WORD PTR[???+ADDR], ?? </code></pre> <p>I tried</p> <pre><code>MOV ANY, 1234h MOV WORD PTR[ANY+ADDR], ANY MOV ?, 1234h MOV WORD PTR[ANY+ADDR], ? MOV r32, 1234h MOV WORD PTR[r32+ADDR], r16 </code></pre> <p>None of these patterns compile in Ollydebugger how do I do this? (I would like to avoid scripts for such a easy task.</p> <p>This one below compiles and works,</p> <pre><code>MOV r32, 0x1234 </code></pre> <p>but how do I combine it with </p> <pre><code>MOV WORD PTR[r32+ADDR], r16 </code></pre>
OllyDebugger How to use Find Sequence of commands with wildcard 32bit registers
|ollydbg|
<p>UAC has certain heuristics that will cause a file to request elevation unless a manifest exists that states otherwise. Such heuristics include files that seem to be setup programs for some software. But there are more heuristics and other situations where elevation is assumed to be required.</p> <p>If the executable has no manifest, you need to add one. Otherwise you may have to modify the existing one.</p> <p>You can tell by loading it into a resource editor or resource viewer such as:</p> <ul> <li><a href="http://www.angusj.com/resourcehacker/" rel="nofollow noreferrer">http://www.angusj.com/resourcehacker/</a></li> <li><a href="http://www.resedit.net/" rel="nofollow noreferrer">http://www.resedit.net/</a></li> </ul> <p>... and so on. Check out the answers to this question: <a href="https://reverseengineering.stackexchange.com/q/2319">Freely available resource hacking applications</a> ...</p> <h3>Workarounds are:</h3> <ul> <li>this can be done by setting the value <code>level="asInvoker"</code> in element <code>requestedExecutionLevel</code> of the manifest (see <a href="https://superuser.com/questions/24631/prevent-elevation-uac-for-an-application-that-doesnt-need-it">here</a> and more generally <a href="http://msdn.microsoft.com/en-us/library/aa905330.aspx" rel="nofollow noreferrer">here</a> and <a href="http://www.codeproject.com/Articles/17968/Making-Your-Application-UAC-Aware" rel="nofollow noreferrer">here</a>)</li> <li>or if you don't have the requirement that the file be saved and can instead provide a script to launch it, you can set an environment variable (<code>set __COMPAT_LAYER=RUNASINVOKER</code>) as explained <a href="https://superuser.com/a/450503">here</a></li> </ul> <p>Unfortunately this is somewhat of a science to get right.</p>
4381
2014-05-20T03:56:17.213
<p>Whenever I save an executable in OllyDBG (Right-click, Copy to executable, All modifications then Save File), the saved executable asks for administrator privileges when I run it.</p> <p>I tried opening OllyDBG as a regular user and then saving the file, but no luck. I also tried manipulating the file's permissions, but no luck either.</p> <p>Is there a way to save a file so that regular users can run it?</p>
OllyDBG causes executables saved by it to ask for administrator privileges when run
|ollydbg|executable|
<p><code>The alias needs to be evaluated</code> <strong>everytime</strong> the break point is hit<br> else it will print the old alias only<br> to force alias evaluation` enclose the .echo and other commands inside a <strong>.block{}</strong> </p> <pre><code>crefil:\&gt;dir /b CreateFile.cpp crefil:\&gt;type CreateFile.cpp #include &lt;stdio.h&gt; #include &lt;windows.h&gt; int main (void) { PWIN32_FIND_DATA lpFindFileData = (PWIN32_FIND_DATA) calloc(1 , sizeof( WIN32_FIND_DATA)); FILE *fp; errno_t err; if (lpFindFileData) { HANDLE hFind = FindFirstFile("*.*",lpFindFileData); if ( hFind != INVALID_HANDLE_VALUE ) { do { printf("%s\n",lpFindFileData-&gt;cFileName); if ( (err = fopen_s(&amp;fp,lpFindFileData-&gt;cFileName,"rb") ) == 0 ) if (fp) fclose(fp); }while( ( FindNextFile(hFind,lpFindFileData) ) != FALSE ); FindClose(hFind); free(lpFindFileData); } } return 0; } </code></pre> <p>as in windbg conditional breakpoint </p> <p><strong>crefil:>cdb -c "bp kernel32!CreateFileA \"as /ma ${/v:fname} poi(@esp+4);.block { .echo fname };gc\";g;q" CreateFile.exe</strong></p> <pre><code>0:000&gt; cdb: Reading initial command 'bp kernel32!CreateFileA "as /ma ${/v:fname} poi(@esp+4);.block { .echo fname };gc";g;q' . .. CreateFile.cpp CreateFile.exe CreateFile.obj CreateFile.pdb vc100.pdb quit: </code></pre>
4384
2014-05-20T10:22:15.640
<p>I want to break the debugee as it opens a known file, using <code>windbg</code>. As <code>$scmp</code> doesn't accept direct address, I have to use <code>as</code> (<code>windbg</code> alias command). So, I put a conditional breakpoint at <code>CreateFileA</code>:</p> <pre><code>bu Kernel32!CreateFileA "as /ma ${/v:fName} poi(esp+4);.echo ${fName};...;g" </code></pre> <p>It always prints the same (first) file name. I also tried script files</p> <pre><code>bu ... "$&gt;&lt; bpCmd" bu ... "$$&gt;&lt; bpCmd" </code></pre> <p><em><code>bpCmd</code> content:</em></p> <pre><code>as /ma ${/v:fName} poi(esp+4); .echo ${fName}; ... g; </code></pre> <p>It didn't work as well.</p> <p>So, why <code>as</code> doesn't work in log breakpoints?</p>
Windbg 'as' command in log breakpoint
|windbg|
<p>There are a number of ways to do this. Some people new to signature scanning use MD5 hashes of the entire file. This is <em>VERY</em> flawed, due to the switching of registers or even just the timestamp of the file would change the entire signature.</p> <p>Another method often used is YARA ( <a href="http://plusvic.github.io/yara/" rel="nofollow">http://plusvic.github.io/yara/</a> ). A good example from their webpage:</p> <pre><code>rule silent_banker : banker { meta: description = "This is just an example" thread_level = 3 in_the_wild = true strings: $a = {6A 40 68 00 30 00 00 6A 14 8D 91} $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9} $c = "UVODFRYSIHLNWPEJXQZAKCBGMT" condition: $a or $b or $c } </code></pre> <p>Here they say that one of the A, B or C bytes should be within the file.</p> <p>Another method used (however this is more a Heuristic method) is to detect the ways it tries to hide. Eg obfuscation, encryption odd jumps (like pop, ret to jump to addresses).</p> <p>Another method used often, (although this is less signature based) is IOC, for this see: <a href="http://www.openioc.org/" rel="nofollow">http://www.openioc.org/</a></p> <p>I think you are looking for YARA. Note for writing YARA signatures, good malware/exploits authors randomize everything they can. So try to find the parts that are 'unchangeable'.</p>
4393
2014-05-21T06:21:27.400
<p>I have a problem where I have to create a virus signature for the Stoned Virus (Although this could apply to any virus/file).</p> <p>Let's assume I have a copy of the compiled and decompiled program. I then proceed to identify the most important parts of the virus, that will always be present, in the code. As I understand it I now have to find the corresponding bytes in the compiled virus in order to create a byte signature for that critical part of the virus.</p> <p>How do I proceed to find the corresponding bytes in the compiled source from the code that I identified in the decompiled version?</p> <p>Extra:</p> <ul> <li>The code is in assembly</li> <li>Simply using a hash signature for the entire file is not an option</li> <li>Currently I only have the assembly code, but I can always compile this</li> <li>I am aware that Stoned would usually be located in the boot sector and not in a file. This is only an academic exercise and would be relevant to any virus.</li> </ul> <p>EDIT:</p> <p>The purpose of this is to be able to create virus signatures that can be used to scan a file system to find infected files as well as possibly infected files and variations of the virus code. For this reason I cannot simply use a hash of the entire file and I need to use specific parts of the virus. I can identify those parts but I do not know how to find the matching bytes in the machine code for the viral parts I identified.</p>
How to create a virus signature from decompiled source
|disassembly|assembly|byte-code|malware|
<pre><code>alt + f1 d fs:[30] ollydbg 1.10 raw peb </code></pre> <p>with <code>stolly plugin</code> for 1.10 <code>select the first byte</code> in <code>dump-&gt;right click-&gt;sructure</code> <code>select _peb</code> from drop down box for decoded peb .</p> <pre><code>al+g fs:[30] in ollydbg 2.01 fully decoded _peb in dump / disasm window </code></pre>
4394
2014-05-21T06:44:08.113
<p>I am trying to learn actually how to get to the PEB inside of TEB. I have tried this with <code>windbg</code> but could not manage to dump the PEB with stuff like:</p> <pre><code>!peb </code></pre> <p>or </p> <pre><code>dt nt!_PEB_LDR_DATA </code></pre> <p>And others. But, I could not manage to get the PEB dumped. So also my favorite debugger is still <code>immunitydbg</code>. So, I was trying to get to the information using <code>immunitydbg</code> CLI. But the nearest thing I have managed to get to PEB is dumping the TEB.</p> <pre><code>d fs:[0] </code></pre> <p>So, I there anyhow someway inside of immunity do get the contents of TEB/PEB? I also tried to use the <code>Ollysdbg</code> PE Dump plugin but that only gave me another exe file with different contents. And also i am not sure if the PE Plugin does the right thing for me. </p>
Dump TEB/PEB in immunitydbg
|windows|immunity-debugger|operating-systems|
<p>It's hard to tell without more context, but you're probably looking at a <a href="http://en.wikipedia.org/wiki/Virtual_method_table" rel="nofollow noreferrer">virtual function table (vtable)</a>. See <a href="https://reverseengineering.stackexchange.com/questions/3116/converting-a-virtual-table-from-rdata-into-an-ida-struct">Converting a virtual table from .rdata into an IDA struct</a> for an example.</p>
4398
2014-05-21T22:00:06.593
<p>When using IDA, I can press <kbd>x</kbd> on any subroutine to see where it is called from. Eventually I end up in the <code>.data</code> section. </p> <p>But, what am I looking at when I get to this point ? </p> <p>Are these exports offered by the <code>.dll</code> that I'm looking at ? And, if I get to this point, is it safe to assume that there are no other calls to my function (with the exception of dynamically-generated and/or external calls) ? See reference image below for context.</p> <p><img src="https://i.stack.imgur.com/UKpsu.png" alt="XRefs"></p>
IDA and XRefs in the .data Section
|ida|disassembly|
<p><strong>well after rereading the original question it appears both my answer<br> and the answer i followed up do not give an answer to the original question<br> original question asks about acmdln_dll which is nowhere to be found in vs crt<br> i leave the answer as it is assuming the suffix __dll to be in code that is not native ms like from reactos here</strong></p> <p><a href="http://code.google.com/p/reactos-mirror/source/browse/trunk/reactos/lib/crtdll/misc/GetArgs.c?spec=svn271&amp;r=271" rel="nofollow">http://code.google.com/p/reactos-mirror/source/browse/trunk/reactos/lib/crtdll/misc/GetArgs.c?spec=svn271&amp;r=271</a></p> <p><strong>the answer below is pertinent to _acmdln without the suffix _dll see edit 3 also</strong> </p> <p>the <code>complete source code</code> is available to you for <code>acmdln</code> if you have installed even the <code>express version of visual studio</code>.</p> <p><code>compile a simple hello world with debug info</code> <strong>/Zi</strong> and view the source code as to what it is</p> <p>source file in crt directory of visual studio</p> <pre><code>DS:[00408018]=7C812FBD (kernel32.GetCommandLineA) Jump from __tmainCRTStartup+9B crt0.c:252. _tcmdln = (_TSCHAR *)GetCommandLineT(); </code></pre> <p>here is a relevent disassembly notice the result of GetCommandline being moved to acmdln a global </p> <pre><code>/* * command line, environment, and a few other globals */ #ifdef WPRFLAG wchar_t *_wcmdln; /* points to wide command line */ #else /* WPRFLAG */ char *_acmdln; /* points to command line */ #endif /* WPRFLAG */ char *_aenvptr = NULL; /* points to environment block */ wchar_t *_wenvptr = NULL; /* points to wide environment block */ </code></pre> <p>disassembly </p> <pre><code>004014D9 CALL newheapt._amsg_exit 004014DE POP ECX 004014DF CALL NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetCommandLineA&gt;] ; _tcmdln = (_TSCHAR *)GetCommandLineT(); 004014E5 MOV DWORD PTR DS:[_acmdln], EAX 004014EA CALL newheapt.__crtGetEnvironmentStringsA ; _tenvptr = (_TSCHAR *)GetEnvironmentStringsT(); 004014EF MOV DWORD PTR DS:[_aenvptr], EAX 004014F4 CALL newheapt._setargv ; if ( _tsetargv() &lt; 0 ) 004014F9 TEST EAX, EAX 004014FB JNS SHORT newheapt.00401505 004014FD PUSH 8 ; _amsg_exit(_RT_SPACEARG); 004014FF CALL newheapt._amsg_exit 00401504 POP ECX 00401505 CALL newheapt._setenvp ; if ( _tsetenvp() &lt; 0 ) 0040150A TEST EAX, EAX 0040150C JNS SHORT newheapt.00401516 0040150E PUSH 9 ; _amsg_exit(_RT_SPACEENV); </code></pre> <p><strong>edit 3</strong> </p> <p>from a general search it seems that this is defined in crtdll.dll </p> <pre><code>C:\WINDOWS\system32&gt;grep -rs _acmdln_dll * Binary file crtdll.dll matches Binary file dllcache/crtdll.dll matches ^C C:\WINDOWS\system32&gt; </code></pre> <p>loading the dll in ollydbg _acmdln_dll is exactly same as _acmdln</p> <pre><code>73D91D02 |&gt; \FF15 4410&gt;CALL NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetCommandLineA&gt;] ; [GetCommandLineA 73D91D08 |. A3 CC3EDB&gt;MOV DWORD PTR DS:[_acmdln_dll], EAX 73D91D0D |. FF15 4010&gt;CALL NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetEnvironmentStrings&gt;&gt;; [GetEnvironmentStrings 73D91D13 |. A3 D03EDB&gt;MOV DWORD PTR DS:[73DB3ED0], EAX 73D91D18 |. FF15 0411&gt;CALL NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetVersion&gt;] ; kernel32.GetVersion </code></pre> <p>and this crtdll.dll seems to be from an older windows sdk a brief google yields one page which alludes crtdll.lib belonging to windows sdk 3.5 era</p> <p><a href="http://support.microsoft.com/kb/94248" rel="nofollow">http://support.microsoft.com/kb/94248</a></p>
4400
2014-05-22T01:07:51.720
<p>Does somebody knows what <code>_acmdln_dll</code> is ? I could not find any useful documentation about that. </p> <p>I am asking because I have the following line in the assembly which I try to analyze:</p> <pre><code> MOV EAX, DWORD PTR DS : [_acmdln_dll] </code></pre> <p>After that line I have in register <code>EAX</code> the path of the current process. So my assumption is now the <code>_acmdln_dll</code> stores somehow the path as string sequence. Is that true ? </p> <p>Can someone confirm that or does someone know more informations about <code>_acmdln_dll</code> ?</p>
What does _acmdln_dll?
|disassembly|windows|x86|
<p>This is called "placement <code>new</code>" and was introduced in C++03. The way it works is that one can have, say a C++ class around a set of hardware registers and then use <em>placement <code>new</code></em> to put the class exactly atop those hardware registers. For example, if a hardware-based hardware Random Number Generator (RNG) is defined using 32-bit Control Register, Status Register and Data Register all starting at offset 0x50000600, you could define a class:</p> <pre><code>class RNG_class { private: volatile uint32_t CR; // set to 1 to enable volatile uint32_t SR; // low bit set when next num available volatile uint32_t DR: public; RNG_class() : CR(1) {} uint32_t next() { while (SR&amp;1 == 0); return DR; } }; </code></pre> <p>Elsewhere, then one can instantiate this class as</p> <pre><code>RNG_class RNG* = new(0x50000600) RNG_class(); </code></pre> <p>And one can use it as:</p> <pre><code>r = RNG-&gt;next(); </code></pre> <p>See <a href="https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new">this question</a> for more information.</p>
4402
2014-05-22T07:17:33.703
<p>In the disassembler output (ARM) I see:</p> <pre><code> BLX _Znwj </code></pre> <p>where <code>BLX</code> is ARM procedure call and <code>_Znwj</code> is demangled as</p> <pre><code>$ c++filt _Znwj operator new(unsigned int) </code></pre> <p>What does that <code>operator new</code> do? Is it <code>new</code> or <code>new[]</code>? What type does it return? How do I explicitly call it from C++, something in the <code>operator+(a,b)</code> style?</p> <p>(I know that it is possible to define <code>operator new</code> in a class, but this looks a bit different.)</p>
What is operator new(unsigned int)?
|disassembly|c++|gcc|
<p>The code to detect and print virtual function table pointers is:</p> <pre><code>int isIdentifier(const char* s) { // true if points to [0-9a-zA-Z_]*\x00 if(!isValidPtr(s,0x10)) { return 0; } if(!s[0]) { return 0; } int i; for (i=0; s[i] &amp;&amp; i&lt;512; i++) { if( i/0x10 &amp;&amp; i%0x10 == 0 &amp;&amp; !isValidPtr(s,0x10)) { return 0; } unsigned char c = s[i]; if ('0'&lt;=c &amp;&amp; c&lt;='9' || 'a'&lt;=c &amp;&amp; c &lt;= 'z' || 'A'&lt;=c &amp;&amp; c &lt;= 'Z' || '_' == c) { } else { return 0; } } return !s[i]; } char* isVftPtr(void*addr) { // returns addr of mangled class name (prefix it with _Z to demangle with c++filt) unsigned int* vmtaddr = isValidPtr(addr,4) &amp;&amp; 0 == (3 &amp; *(int*)addr) &amp;&amp; isValidPtr(*(int**)addr,4) ? *(unsigned int**)addr : (void*)0; if (vmtaddr &amp;&amp;isValidPtr(vmtaddr-2,0x20) ) { char**ptypeinfo = ((char***)vmtaddr)[-1]; if (isValidPtr(ptypeinfo,4) &amp;&amp;isValidPtr((char***)ptypeinfo[0]-1,8) &amp;&amp;isValidPtr(((char***)ptypeinfo[0])[-1],8) &amp;&amp;isValidPtr(((char***)ptypeinfo[0])[-1][1],0x20) &amp;&amp;isIdentifier(ptypeinfo[1]) ) { return !strncmp(((char***)ptypeinfo[0])[-1][1], "N10__cxxabiv",12) ? ptypeinfo[1] : 0; } } return 0; } // Usage example: printVfts("pThis", pThis, -8, 0x400) void printVfts(const char*tag, void* addr, int from, int upto) { void** start = addr+from; void** end = addr+upto; DLOG("{ %s ====== printVfts %p (%p..%p)", tag, addr,start,end); void**p; char*n = 0; for(p=addr;p&lt;end;p++) { if (n = isVftPtr(p)) { DLOG("vft at %p [off=0x%x] _Z%s",p,(unsigned)p - (unsigned)addr, n); } } DLOG("} %s ====== printVfts %p", tag, addr); } </code></pre> <p>The code worked on Android/ARM.</p> <p>The function <code>isValidPtr()</code> is given in the question, the logging macro is given below:</p> <pre><code>#include &lt;android/log.h&gt; #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "~~~~~~", __VA_ARGS__) #define DLOG(...) __android_log_print(ANDROID_LOG_DEBUG , "~~~~~~", __VA_ARGS__) </code></pre> <p><strong>And, finally:</strong> <code>printVfts()</code> showed that there is another VFT pointer at offset 0.</p>
4428
2014-05-23T12:58:09.500
<p>I used to think that the pointer to the Virtual Function Table (VFT, also Virtual Method Table, VMT) is the very first 32-bit word of the object binary representation.</p> <p>But now I see a VFT whose index is 13 (!!!!), that is, offset=0x34. (I write "index" because the code to invoke the Qt function <code>o.metaObject()</code> is <code>((func***)o)[13][0](o)</code>). OMG, what is going on? Why the VFT address is located... where?</p> <p>EDIT (after complaints that the question is unclear):</p> <p>Each object with virtual functions has a pointer to the Virtual Function Table. Usually, this is the very first 32-bit value in the object's binary representation (and may be accessed as <code>((void**)objAddr)[0]</code>). But in the example below the offset of VMT pointer is not 0! (Function names may be demangled by <a href="http://linux.die.net/man/1/c++filt" rel="nofollow"><code>c++filt</code></a>; for readability, the class names have been shortened to <code>Abc</code> and <code>Xyz</code>):</p> <pre><code>.text:02EF171C _ZN3XyzC2EP7QObject ; constructor Xyz::Xyz(QObject*), r0 = objAddr, r1 = QObject addr .text:02EF171C PUSH.W {R4-R8,LR} .text:02EF1720 MOV R4, R0 .text:02EF1722 LDR R5, =(_GLOBAL_OFFSET_TABLE_ - 0x02EF1730) .text:02EF1724 MOV R7, R1 .text:02EF1726 BL.W _ZN4AbcdC2EP7QObject ; superclass_constructor(objAddr) .text:02EF172A ; --------------------------------------------------------------------------- .text:02EF172A LDR R3, =(_ZTVN3XyzE_ptr - 0x27E4BE0) ; vtable for Xyz .text:02EF172C ADD R5, PC ; _GLOBAL_OFFSET_TABLE_ .text:02EF172E MOV R6, R4 .text:02EF1730 MOV R1, R7 .text:02EF1732 LDR R3, [R5,R3] ; _ZTVN3XyzE_ptr ; pointer to vtable for Xyz .text:02EF1734 ADDS R3, #8 ; *_ptr points to the (-2)nd element of VMT .text:02EF1736 STR.W R3, [R6],#0x34 ; OOPS! the offset is 0x34 !!! </code></pre> <p><em>I want to be able to locate the pointer to VMT for any object,</em> but as the example above shows, the pointer to VMT is not necessarily <code>((void**)objAddr)[0]</code>.</p> <p>So the question is:</p> <p>1) <strong><em>why the VMT pointer is in the middle of the object's binary representation?</em></strong> There must be something specific about this place.</p> <p>2) <strong><em>how do I find out where the VMT pointer actually is?</em></strong> (Ideally, at run-time given the object address. I have the code to tell a valid address from an invalid one. I'm interested in GCC for Android/ARM, although techniques for different platforms may turn out to be applicable.)</p> <p>PS the code to detect a valid address on Android is:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; int isValidPtr(const void*p, int len) { if (!p) { return 0; } int ret = 1; int nullfd = open("/dev/random", O_WRONLY); // does not work with /dev/null !!! if (write(nullfd, p, len) &lt; 0) { ret = 0; /* Not OK */ } close(nullfd); return ret; } </code></pre> <p>UPDATE</p> <p>In the following example, the VMT offset is 0:</p> <pre><code>class Base { public: int x,y; }; class Derived: public Base { public: int z; Derived(); virtual int func(); virtual int func2(); }; </code></pre> <p>Coercion from <code>Base*</code> to <code>Derived*</code> compiles to: <code>SUBS R0, #4</code></p> <pre><code>int test3(Base*b) { Derived*d = (Derived*)b; int r = addDerived(*d); return r; } ; test3(Base *) _Z5test3P4Base CBZ R0, loc_1C7A SUBS R0, #4 B.W _Z10addDerivedR7Derived ; </code></pre> <p>UPDATE2</p> <p>I tried</p> <pre><code>struct Cls2 { unsigned x[13]; Derived d; Cls2(); }; </code></pre> <p>and here's the disassembly:</p> <pre><code>.text:00001CE2 _ZN4Cls2C2Ev ; Cls2::Cls2(void) .text:00001CE2 PUSH {R4,LR} .text:00001CE4 MOV R4, R0 .text:00001CE6 ADD.W R0, R0, #0x34 .text:00001CEA BL _ZN7DerivedC2Ev ; Derived::Derived(void) .text:00001CEE MOV R0, R4 .text:00001CF0 POP {R4,PC} </code></pre> <p>That is, the VFT pointer of <code>Cls2::d</code> will indeed be at offset 0x34, but there's no <code>STR.W R3,[R6],#0x34</code>, so it is not #2 suggested by Willem Hengeveld.</p> <p>BUT if we comment out the constructor,</p> <pre><code>struct Cls2 { unsigned x[13]; Derived d; // Cls2(); }; </code></pre> <p>in</p> <pre><code>int testCls2() { Cls2 c; return c.d.func2(); } </code></pre> <p>we get</p> <pre><code>.text:00001C9E _Z8testCls2v .text:00001C9E var_18 = -0x18 .text:00001C9E PUSH {LR} .text:00001CA0 SUB SP, SP, #0x4C .text:00001CA2 ADD R0, SP, #0x50+var_18 .text:00001CA4 BL _ZN7DerivedC2Ev ; Derived::Derived(void) .text:00001CA8 ADD R0, SP, #0x50+var_18 .text:00001CAA BL _ZN7Derived5func2Ev ; Derived::func2(void) .text:00001CAE ADD SP, SP, #0x4C .text:00001CB0 POP {PC} </code></pre> <p>which is very similar to the original code BUT in my case the VMT <code>vtable for Xyz</code> is written from <code>Xyz::Xyz()</code> and not from the enclosing function.</p>
Where the pointer to virtual function table is located?
|c++|arm|virtual-functions|gcc|
<p>I think the second vector of three floats is the <a href="http://en.wikipedia.org/wiki/Normal_vector" rel="nofollow">normal vector</a>. Which is basically the front facing direction of the vertex. It looks like the length is 1 so it's normalized which would correspond well with what you'd expect of a normal vector. The last two I believe are <a href="http://en.wikipedia.org/wiki/UV_mapping" rel="nofollow">UV mapping</a> coordinates for texturing but it's hard to be positive without full data files.</p>
4434
2014-05-23T16:04:07.677
<p>I am reverse engineering a 3d file format for a game. I know the file is a mesh since I was able to identify the XYZ Coordinates for each vector as well as the MeshFaces. Each Vector XYZ Coordinate has 3 floats like so:</p> <p>[this is pulled from an actual file]</p> <pre><code>41FC39C0 73480640 3AC87240 6038BF3E DF545D3F E620ACBE 00000000 0000403F </code></pre> <p>And this is the float representation of the hex:</p> <pre><code>-2.9060214 2.0981719 3.7934709 = X Y Z 0.37347698 0.86457628 -0.3361885 0.0 0.75 = Not sure what this this is. </code></pre> <p>I want to say the first 2 values could possibly be <code>tU</code>, <code>tV</code> values, but from what I know with DirectX, texture coordinates are usually between 0 and 1. Even though this file, the numbers fit between, I could bring up another file when those first 2 numbers are something like -.50 or even above 1 so I can't say they are text coordinates for sure.</p> <p>The last 3 values I have no idea.</p> <p>This 3d Mesh File is for a online game that uses a custom built DirectX 9 engine and from what I gather so far, is loosely based on Direct3D's .X file specifications.</p> <p>I am able to pull out the XYZ coordinates into a list that can be imported into Cinema 4D and I have confirmed the XYZ is accurate based on the object that is drawn. In this case, a rock.</p> <p>Here is floats for the first 3 data points within this file:</p> <pre><code>1. -2.9060214 2.0981719 3.7934709 0.37347698 0.86457628 -0.3361885 0.0 0.75 2. -2.7679636 2.0897043 2.6395969 0.16878456 0.98563963 5.1173517e-003 0.0 0.5 3. -2.7679636 6.2550635 2.7174740 0.20584901 -0.96193141 -0.17976092 1.0 0.5 </code></pre> <p>From my experience with reverse engineering 3D date, if a floating point number is exponential, it most likely is being read wrong, so the '5.1173517e-003' on the 2nd line towards the end may not even be a floating point number, but then its other possible values:</p> <pre><code>INT8 117 UINT8 117 INT16 -20619 UINT16 44917 INT32 1000845173 UINT32 1000845172 HALF FLOAT -0.11651611 </code></pre> <p>don't make much sense either.</p>
What kind of data is this within this 3D mesh file format?
|binary-analysis|
<p>JE checks the zero flag (ZF). So as long as ZF is not modified you can jump any time you want. The same to other jump instructions</p>
4436
2014-05-23T23:44:57.003
<p>I wanted to know if a jump instruction as <code>JE</code> must directly follow to a <code>CMP</code> instruction. Until now, I did always see that first a <code>CMP</code> comes and after that a <code>JMP</code>. But today I have discover the following:</p> <pre><code>... CMP DWORD PTR SS:[EBP+0xC], EAX MOV ECX, DWORD PTR SS:[EBP+0x18] PUSH ESI MOV ECX, DWORD PTR SS:[EBP+0x18] MOV DWORD PTR SS:[ECX],EAX MOV EAX, DWORD PTR SS:[EBP+0x10] MOV DWORD PTR SS:[EDI], 0x1 JE SHORT crtdll.6C250E66 .... </code></pre> <p>First of all, I am beginner. So, I try to understand the assembly language. Logically, I would say that the <code>JE</code> instruction is related to the <code>CMP</code> instruction at the beginning of that sequence. </p> <p>So, my self-explanation was that we first compare, then do some <code>MOV</code> and <code>PUSH</code> operations, after that all we are jumping, is that right?</p> <p>But, as I mentioned above, normally the jump comes in the next line after the comparison, could one say the reason for that late jump instruction here ? Or is it normal ?</p>
Does a JE must follow directly to an CMP?
|assembly|x86|
<p>Use <code>GetModuleHandle()</code> to get the base address of the module and the offset. The offset is just <code>current address - base address</code>.</p>
4448
2014-05-25T20:20:23.200
<p>Modern exploits use different techniques to bypass ASLR. One of the technique used in some IE exploits is to leak memory using a BSTR overwrite.</p> <p>How can an attacker leak memory, and how can he use it to effectively bypass ASLR?</p>
Reading Memory to bypass ASLR
|exploit|vulnerability-analysis|
<p>One way to patch the instruction <code>lea eax, [edi-0Ch]</code>, is to create an advanced detour inside the code to your own custom .text segment and then back again to the code.</p> <p>For a regular <code>mov reg32, imm32</code> opcode you need at least 5 bytes of space which will obviously never fit into the 3 byte opcode.</p> <p>For a detour opcode sequence, you need to either craft your own relative jump (5 bytes), or use the shortest syntax for absolute jump (6 bytes):</p> <pre><code>PatchStart: push loc_patch1 ;; push address of the patch code ret ;; pop address and jump to it </code></pre> <p>So if the code originally looked like this:</p> <pre><code>.text:008EC44A align 10h .text:008EC450 loc_8EC450: .text:008EC450 lea eax, [edi-0Ch] ;; 3 bytes .text:008EC453 push eax ;; 1 byte .text:008EC454 call sub_A00890 ;; 5 bytes .text:008EC459 </code></pre> <p>You can replace it with:</p> <pre><code>.text:008EC44A align 10h .text:008EC450 loc_8EC450: .text:008EC450 push loc_patch1 ;; 5 bytes .text:008EC455 ret ;; 1 byte .text:008EC456 nop ;; pad other 3 bytes .text:008EC457 nop .text:008EC458 nop .text:008EC459 </code></pre> <p>And now for the patch itself:</p> <pre><code> loc_patch1: mov eax, PatchedValue ;; lea eax,[edi-0Ch] push eax call sub_A00890 push loc_8EC459 ;; jump back to source ret </code></pre> <p>There are some performance penalties for long absolute jumps, but in the end it will get your executable patched without any tedious relocation needed.</p> <p>If you wish to craft your own long relative jumps/calls then the opcodes (5 bytes) look like this:</p> <pre><code>;; call +0xCAFE E8 FE CA 00 00 ;; jmp +0xCAFE E9 FE CA 00 00 </code></pre> <p>The bonus is that relative jumps require only 5 bytes. So if you create a new second text segment or replace some unused code inside the original .text segment, you'll be good to go.</p>
4453
2014-05-26T15:14:14.387
<p>I need a little help from you guys! At present, I'm working on an IDA Pro Database in order to create a patch for an executable, and I'm totally stuck on editing the following sub:</p> <pre><code>.text:008EC420 ; char __thiscall sub_8EC420(MyClass *this) .text:008EC420 sub_8EC420 proc near .text:008EC420 var_8 = dword ptr -8 .text:008EC420 var_4 = dword ptr -4 .text:008EC420 sub esp, 8 .text:008EC423 push ebx .text:008EC424 mov ebx, ecx .text:008EC426 cmp dword ptr [ebx+79954h], 0 .text:008EC42D mov [esp+0Ch+var_4], ebx .text:008EC431 mov [esp+0Ch+var_8], 0 .text:008EC439 jle loc_8EC4F2 .text:008EC43F push ebp .text:008EC440 push esi .text:008EC441 push edi .text:008EC442 lea edi, [ebx+114h] .text:008EC448 jmp short loc_8EC450 .text:008EC44A align 10h .text:008EC450 loc_8EC450: .text:008EC450 lea eax, [edi-0Ch] .text:008EC453 push eax .text:008EC454 call sub_A00890 .text:008EC459 mov esi, eax .text:008EC45B add esp, 4 .text:008EC45E cmp esi, 0FFFFFFFFh .text:008EC461 jnz short loc_8EC472 .text:008EC463 mov dword ptr [edi], 0 .text:008EC469 mov dword ptr [edi-4], 0FFFFh .text:008EC470 jmp short loc_8EC480 .text:008EC472 loc_8EC472: .text:008EC472 push esi .text:008EC473 call sub_A00870 .text:008EC478 add esp, 4 .text:008EC47B mov [edi], eax .text:008EC47D mov [edi-4], esi .text:008EC480 loc_8EC480: .text:008EC480 xor ebp, ebp .text:008EC482 cmp [edi+0ECh], ebp .text:008EC488 jbe short loc_8EC4D2 .text:008EC48A lea esi, [edi+0BCh] .text:008EC490 loc_8EC490: .text:008EC490 lea ecx, [esi-0Ch] .text:008EC493 push ecx .text:008EC494 call sub_A00890 .text:008EC499 mov ebx, eax .text:008EC49B add esp, 4 .text:008EC49E cmp ebx, 0FFFFFFFFh .text:008EC4A1 jnz short loc_8EC4B2 .text:008EC4A3 mov dword ptr [esi], 0 .text:008EC4A9 mov dword ptr [esi-4], 0FFFFh .text:008EC4B0 jmp short loc_8EC4C0 .text:008EC4B2 loc_8EC4B2: .text:008EC4B2 push ebx .text:008EC4B3 call sub_A00870 .text:008EC4B8 add esp, 4 .text:008EC4BB mov [esi], eax .text:008EC4BD mov [esi-4], ebx .text:008EC4C0 loc_8EC4C0: .text:008EC4C0 add ebp, 1 .text:008EC4C3 add esi, 14h .text:008EC4C6 cmp ebp, [edi+0ECh] .text:008EC4CC jb short loc_8EC490 .text:008EC4CE mov ebx, [esp+18h+var_4] .text:008EC4D2 loc_8EC4D2: .text:008EC4D2 mov eax, [esp+18h+var_8] .text:008EC4D6 add eax, 1 .text:008EC4D9 add edi, 3E4h .text:008EC4DF cmp eax, [ebx+79954h] .text:008EC4E5 mov [esp+18h+var_8], eax .text:008EC4E9 jl loc_8EC450 .text:008EC4EF pop edi .text:008EC4F0 pop esi .text:008EC4F1 pop ebp .text:008EC4F2 loc_8EC4F2: .text:008EC4F2 mov al, 1 .text:008EC4F4 pop ebx .text:008EC4F5 add esp, 8 .text:008EC4F8 retn .text:008EC4F8 sub_8EC420 endp </code></pre> <p>The <code>MyClass</code> entity looks like this:</p> <pre><code>struct MyClass // 502076 bytes { void *VFT; // 4 bytes MyStruct Structs[500]; // 498000 bytes = sizeof(MyStruct)=996 * 500 // more data... }; </code></pre> <p>In order to allow <code>MyClass</code> to parse and manage more <code>MyStruct</code> instances, I enlarged the <code>.data</code> segment of the executable by <code>sizeof(MyStruct1)=996 * 1000 = 996000 bytes</code> and I appended a new <code>MyStruct[1000]</code> at the end of it. Now, all what I need to do is to shift every memory pointer trying to access the <code>MyClass.Structs</code> memory region to the <code>MyStruct[1000]</code> memory region. Many modifications were pretty easy to achieve, but I really don't know how to deal with this one.</p> <p>The method <code>sub_8EC420</code> iterates through every <code>MyStruct</code> instance in <code>MyClass.Structs</code> getting a specific field and doing some operations with it:</p> <pre><code>char *v2 = &amp;this-&gt;Structs[0].ValueAt272; // offset = MyClass + 276 | MyClass-&gt;Structs + 272 do { // operations... v2 += 996; // sizeof(MyStruct) } while ( ... ); </code></pre> <p>In order to successfully redirect the memory pointer to the new <code>MyStruct[1000]</code> array located at the end of the <code>.data</code> segment, I must change the following instruction:</p> <pre><code>.text:008EC442 lea edi, [ebx+114h] // offset = MyClass + 276 | MyClass-&gt;Structs + 272 // bytes = 8D BB 14 01 00 00 </code></pre> <p><code>EBX</code> is the register that points to my <code>MyClass</code> instance offset. But I can't transform it into this:</p> <pre><code>.text:008EC442 mov edi, 2DABF84h; nop; </code></pre> <p>Because, as you can see, just after, the <code>EDI</code> register value is being used and this would lead to bad results:</p> <pre><code>.text:008EC450 lea eax, [edi-0Ch] </code></pre> <p>I also tried an edited <code>LEA</code> approach but it's not producing good results either:</p> <pre><code>.text:008EC442 lea edi, [ebx+14A027Ch] // offset = MyStruct[1000] (0x02DABE74) - MyClass Instance (0x190BD08) + 272 // bytes = 8D BB 7C 02 4A 01 </code></pre> <p>On the top of that, inserting additional bytes to this sub completly breaks my IDA Pro database. So... how should I deal with this?</p>
Redirecting/Remapping/Rerouting a Memory Access
|ida|disassembly|assembly|memory|
<p>A writable header is a side-effect of the low alignment. More interestingly, an <em>executable</em> header is possible, too, bypassing DEP restrictions even when set to enable for all processes. That allows code to execute directly from the header, which would normally not be allowed. When used for a DLL, the ImageBase can become the entrypoint (i.e. call LoadLibrary; call eax), which might be a bit unexpected.</p> <p>Other implications include that some tools cannot disassemble or dump such files properly. A low alignment allows for the creation of very small files (as small as 268 bytes on 64-bit or 255 bytes on 32-bit Vista and later systems (XP allows the file to be 233 bytes long)), by overlapping the tables, and even removing all of the sections. This small size has been proven to be sufficient for a downloader.</p>
4457
2014-05-27T07:27:00.773
<p>I only found this term "low alignment mode" in the <a href="https://code.google.com/p/corkami/wiki/PE" rel="nofollow">corkami wiki</a>.</p> <blockquote> <ul> <li><p>standard mode: 200 &lt;= FileAlignment &lt;= SectionAlignment and 1000 &lt;= SectionAlignment</p></li> <li><p>low alignment: 1 &lt;= FileAlignment = SectionAlignment &lt;= 800</p></li> </ul> </blockquote> <p>The numbers are hex values.</p> <p>Some possible implications are described by <a href="https://media.blackhat.com/bh-us-11/Vuksan/BH_US_11_VuksanPericin_PECOFF_WP.pdf" rel="nofollow">ReversingLabs</a> </p> <p>It seems low alignment is necessary to make the PE Header writable. However, FileAlignment and SectionAlignment have to be lower than or equal to 200h, which is more restrictive than the low alignment mode above. So I am not sure if this is really a consequence of low alignment or if low alignment mode is just one part of that <em>trick</em>. </p> <p>In addition it seems that the virtual addresses have to be equal to the physical ones.</p> <p>I would like to understand this better.<br> My questions are: What implications has the low alignment mode? How is the way changed the loader loads the PE? Why is it that way?</p>
What implications has the low alignment mode of a PE file?
|pe|
<p>Got it. Here's how to calculate, using your first string as a simple example:</p> <pre><code>1f456e01 </code></pre> <p>First, we rearrange the packet, omitting the checksum.</p> <pre><code>1f 01 </code></pre> <p>Then prepend the values A3 02:</p> <pre><code>a3 02 1f 01 </code></pre> <p>Then calculate the checksum by starting with a sum of 0, multiplying the sum by 33 (decimal) each time and adding the value of the next byte.</p> <p>Here it is in C with a few of your sample strings for illustrations. Note that this assumes a little-endian machine (e.g. x86).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; const unsigned char s1[]= "\x0e\x01\x72\x00\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x31\x32\x31\x31\x31\x31\x31\x00"; const unsigned char s2[]="\x2b\x4f\x70\x7f"; const unsigned char s3[]="\x1f\x46\x6e\x02"; uint16_t verify(const unsigned char *pkt, size_t sz) { uint16_t sum = 0xa3 * 33 + 2; int i; for (i=0; i &lt; sz; ++i) { if ((i != 1) &amp;&amp; (i != 2)) sum = sum*33 + pkt[i]; } return sum; } int main() { printf("calculated %4.4x, actual %4.4x\n", verify(s1, sizeof(s1)-1), *(uint16_t *)(&amp;s1[1])); printf("calculated %4.4x, actual %4.4x\n", verify(s2, sizeof(s2)-1), *(uint16_t *)(&amp;s2[1])); printf("calculated %4.4x, actual %4.4x\n", verify(s3, sizeof(s3)-1), *(uint16_t *)(&amp;s3[1])); return 0; } </code></pre> <p>Here's the output from that program:</p> <pre><code>calculated 7201, actual 7201 calculated 704f, actual 704f calculated 6e46, actual 6e46 </code></pre> <h1>Update:</h1> <p>I thought it might be useful to describe how I came about this answer so that it may help others in the future. First, as other answers note, your packets that were identical except for a single bit were invaluable in determining the general checksum algorithm (multiplying by 33 and adding the next byte). </p> <p>What remained was to determine the starting position which could have included the first byte (the one you're calling the <em>index byte</em>) and/or the length. When I compared two packets which were identical except for the index byte, and assuming a linear relationship also for these bytes, it was easy to determine that the index byte was "next to" the data bytes for calculation purposes. </p> <p>When I did that, all of the complete packets among your samples differed from my calculated value (long packets all by the constant <code>0xe905</code> and short packets by <code>0x6a45</code>). Since the checksum is only 2 bytes, I guessed that there might be a 2-byte initialization value and simply wrote a small program to try all combinations. I chose one combination (A3 02) but in fact, there are exactly eight combinations that work -- all you need is something that ultimately evaluates to <code>0x1505</code> (5381 decimal).</p>
4460
2014-05-27T09:02:05.960
<p>I am trying to reverse engineer a 16 bit checksum algorithm of one relatively old (10 years) LAN game that is no longer supported nor has source code available. As it seems, data packets don't have standard structure when it comes to placing checksum bytes:</p> <pre><code>Example 1: 1f456e01 </code></pre> <p>Where first byte <code>1f</code> seems to repeat itself in each packet and I assume it doesn't take part in generating checksum. </p> <p>Next two bytes <code>456e</code> represent a checksum that presumably is a variation of <code>CRC-CCITT</code> with non-standard polynomial. </p> <p>Lastly, <code>01</code> byte represents data.</p> <p>Here are few more examples of packets with various data values:</p> <pre><code>1f466e02 1f496e05 1f4b6e07 1f4c6e08 </code></pre> <p>I wish I could post more diverse values but these are only ones I've been able to capture so far.</p> <p>I tried fiddling with <a href="http://reveng.sourceforge.net/" rel="noreferrer">reveng</a> to reverse engineer the polynomial with following command:</p> <pre><code>reveng -w 16 -s 01456e 02466e 05496e </code></pre> <p>Here the checksum bytes are relocated at the end, as reveng expects them in this format. But this gave no results.</p> <p>I have tried comparing these checksums to most if not all common crc algorithms using online calculators but none of them give even close outputs to those above.</p> <p>Honestly, I don't know where else to look.</p> <p>Any hints/help or anything at all is much appreciated.</p> <p><strong>EDIT:</strong></p> <p>I managed to capture some more samples, however they are slightly different in terms of structure:</p> <p>Example 1:</p> <pre><code>0e ed76 00 312e362e37544553540000000000000000000000000000000000000000 00 </code></pre> <p>Here the first byte <code>0E</code> represents a sort of index, that I still think doesn't take part in generating checksum. Then comes two byte checksum <code>ED76</code> followed by <code>00</code> sort of separator (newline?) byte that I also think doesn't take part in computing checksum. Afterwards follows data sequence: <code>312e362e37544553540000000000000000000000000000000000000000</code> which finally is proceeded by <code>00</code> terminating character that I also think has nothing to do with checksum.</p> <p>I can manipulate with the data part of this sequence of bytes so here are some more examples:</p> <pre><code>Example 2: HEX: 0E109D00414141414141414141414141414141414141414141414141414141414100 ASCII: ....AAAAAAAAAAAAAAAAAAAAAAAAAAAAA. Example 3: HEX: 0E8DC300424242424242424242424242424242424242424242424242424242424200 ASCII: ....BBBBBBBBBBBBBBBBBBBBBBBBBBBBB. Example 4: HEX: 0E403500313131313131313131313131313131313131313131313131313131313100 ASCII: .@5.11111111111111111111111111111. Example 5: HEX: 0E34CF00353535353535353535353535353535353535353535353535353535353500 ASCII: .4..55555555555555555555555555555. Example 6: HEX: 0E3E0C00313233343536373839304142434445464748494A4B4C4D4E4F5051525300 ASCII: .&gt;..1234567890ABCDEFGHIJKLMNOPQRS. </code></pre> <p><strong>EDIT 2:</strong> More samples added, checksum bytes reversed to show the actual 16 bit int (little endian)</p> <pre><code>Data Checksum 0x01 0x6E45 0x02 0x6E46 0x03 0x6E47 0x0001 0x3284 0x0002 0x3285 0x0003 0x3286 0x0104 0x32A8 0x0005 0x3288 0x0903 0x33AF 0x0106 0x32AA 0x3600 0x0AAE 0xAD00 0x1A05 0xF300 0x230B 0xF400 0x232C 0xF500 0x234D 0xF600 0x236E 0xF700 0x238F 0xF800 0x23B0 0xFE00 0x2476 0xA800 0x1960 0xE200 0x20DA 0xE500 0x213D 0xEE00 0x2266 0x7300 0x128B 0x7600 0x12EE 0xF700 0x238F 0xB400 0x1AEC 0xB800 0x1B70 0xBC00 0x1BF4 0x015E00 0xF68B 0x013D00 0xF24A 0x011C00 0xEE09 </code></pre> <p><strong>EDIT 3</strong>: More samples that might make it easier to see the pattern:</p> <pre><code>Checksum Data (ASCII) 3540 11111111111111111111111111111 3561 11111111111111111111111111112 3582 11111111111111111111111111113 3981 11111111111111111111111111121 39A2 11111111111111111111111111122 c1a1 11111111111111111111111111211 4DC1 11111111111111111111111112111 5de1 11111111111111111111111121111 7201 11111111111111111111111211111 </code></pre> <p><strong>EDIT 4:</strong></p> <p>There was a typo in one of <strong>EDIT 3</strong> samples - correct checksum for <code>11111111111111111111111112111</code> is <code>4DC1</code> instead of <code>C10E</code>. Edited original sample. Apologies to everyone who lost their time because of this.</p> <p><strong>EDIT 5:</strong></p> <p>It turns out, the index byte does play a role in calculating checksum, here is one particular example proving it:</p> <pre><code>INDEX CHECKSUM PAYLOAD 0x2B 0x704E 0x7E 0x3E 0x72C1 0x7E Same payload has different checksum for different indexes. (checksum bytes reversed to show the actual 16 bit int) </code></pre> <p>Some more samples:</p> <pre><code>INDEX CHECKSUM PAYLOAD 0x3E 0x72C0 0x7D 0x1F 0x6E45 0x01 0x2B 0x704F 0x7F </code></pre> <p><strong>Epilogue</strong></p> <p>Please see the accepted answer for the exact algorithm. Special thanks to <strong>Edward</strong>, <strong>nrz</strong> and <strong>Guntram Blohm</strong>; solving this would take a lifetime without your help guys! </p>
Guessing CRC checksum algorithm
|deobfuscation|decryption|networking|
<p>Assuming you want to see it in Windbg.</p> <p>You can follow this walk through for each pointer points to successive <code>LDR_DATA_TABLE_ENTRY</code> the output is from <code>calc.exe</code>. </p> <pre><code>0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(@$peb+c)+c) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\calc.exe" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(@$peb+c)+c)) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\ntdll.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(@$peb+c)+c))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\kernel32.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(@$peb+c)+c)))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\SHELL32.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(@$peb+c)+c))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\ADVAPI32.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\RPCRT4.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\Secur32.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\GDI32.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\USER32.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\msvcrt.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\SHLWAPI.dll" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))))))) +0x024 FullDllName : _UNICODE_STRING "" 0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))))))))) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\calc.exe" </code></pre> <p><strong>an alternate representation of the above method</strong></p> <pre><code>lkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink) +0x024 FullDllName : _UNICODE_STRING "C:\Program Files\Windows Kits\8.0\Debuggers\x86\windbg.exe" lkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink-&gt;Flink) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\ntdll.dll" lkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink-&gt;Flink-&gt;Flink) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\kernel32.dll" lkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink-&gt;Flink-&gt;Flink-&gt;Flink) +0x024 FullDllName : _UNICODE_STRING "C:\WINDOWS\system32\ADVAPI32.dll" </code></pre>
4465
2014-05-27T12:15:13.320
<p>I am trying to get the base address of <code>ntdll.dll</code> over the <code>PEB</code>. So, what I did was to dump the <code>PEB</code> (<code>d fs:[30]</code>). Then, I tried to get to <code>PEB_LDR_DATA</code> over the offset <code>0xC</code>. Over the offset <code>0x1C</code> of <code>PEB_LDR_DATA</code> I found the the pointer of <code>InInitializationOrderModuleList</code> and I was told that I can find the <code>ntdll.dll</code> address there. And that I should first find the address of <code>kernel32.dll</code> (which is always the second entry). So, I was able to find the address of <code>kernel32.dll</code> but it seems like I can't find the address of <code>ntdll.dll</code>. </p> <pre><code>00251ED8 .ܛὈ%Ậ%ὐ%Ẵ%.....@ᐴ@怀.TVٜڔ倀...뉨粘뉨粘趨即....ꮫꮫꮫꮫ......ܨ‐%Ỡ%‘%Ứ% 00251F58 †%Ẽ%.粑Ⱘ粒怀:Ȉ퀨粘⅘粓䀄耈..니粘니粘뾿䠂....ꮫꮫꮫꮫ......ܵC:\WINDOWS\system32\ 00251FD8 kernel32.dll.ꮫꮫꮫꮫﻮﻮﻮ......߁⅐%Ὀ%⅘%ὐ%Ⅰ%὘%.粀똾粀耀@Bᾰ%Ῐ%䀄耈..늰粘늰粘뿀䠂 00252058 ....ꮫꮫꮫꮫ.....ߎC:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b 002520D8 9a1e18e3b_9.0.21022.8_x-ww_d08d0375\MSVCR90.dll.ꮫꮫꮫꮫ.....ߩẬ%‐% 00252158 Ẵ%‘%Ẽ%†%.硒ⵀ硔 .¾À⁸%℠%䀆逈..닀粘닀粘㷎䜱....ꮫꮫꮫꮫ....ߊ.ᓮîŸ%Ÿ%ﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮ </code></pre> <p>This is the part where I have found the <code>kernel32.dll</code>. But in the fact of that this a linked list. Shouldn't I be able to find <code>ntdll.dll</code> too? </p> <p>When, I open up the window of "Executable Modules" I can see the <code>ntdll.dll</code> but it seem I am not able to find the base address inside of the <code>Struct</code>. </p> <p>Please tell me if you need clarification or if I am grievously mistaken.</p>
Where is ntdll.dll?
|windows|assembly|memory|immunity-debugger|
<p>This seems to be ARM PIC (Position-Independent) code, where the address is given relative to the program counter. Ida detects this and shows the "real" address. </p> <p>Unfortunately, you didn't post any code around the your single statement, so i'm using one of my own disassemblies to show you:</p> <pre><code>.text:00062454 LDR R3, [R4,#8] .text:00062458 MOV R0, #0x2C ; ',' .text:0006245C LDR R1, =(unk_218172 - 0x62474) &lt;--- a .text:00062460 MOV R5, #0 .text:00062464 MOV R2, #4 ; n .text:00062468 STRB R0, [R3,#0x12] .text:0006246C ADD R1, PC, R1 &lt;--- b .text:00062470 LDR R3, [R4,#8] .text:00062474 ADD R0, R3, #0x30 ; dest .text:00062478 STR R1, [R3,#8] .text:0006247C STR R1, [R3,#0x14] </code></pre> <p>The code loads some value into R1 (a), then (b) adds PC to it. So, the value of the register is supposed to be a pointer into memory, but beause PC gets added later, the value that is loaded at 2645C wouldn't make any sense. Ida detects the ADD instruction, and shows the LDR instruction in a way that lets you see where it's supposed to point to.</p> <p>The fact that the "correcting offset" of 0x62474 is not the address of the <code>ADD</code> instruction is because of pipelining within the processor; at the moment the <code>ADD</code> gets executed, the next instructions have already been read, so PC is two instructions "behind" where the <code>ADD</code> instruction is located.</p> <p>(The reason why the compiler produces this kind of code is, when the same code gets loaded at a different address later it stays valid, even without the relocation patching the linker/loader would have to do otherwise. That's called PIC, or Position-independent code.)</p>
4474
2014-05-28T18:58:41.147
<p>What is this instruction trying to do?</p> <pre><code> .text:4044A5EC LDR R5, =(unk_40885080 - 0x4044A5F8) </code></pre> <p>Looking at the value of unk_40885080 it holds a value of 20 in the .data segment.</p>
Understanding unknown in IDA
|ida|disassembly|
<p>I was able to get that firmware to a shell by doing the following:</p> <ol> <li>Unpacking the squashfs image</li> <li>Create a filesystem image formatted to ext2 and copying the unpacked squashfs contents into that, and using that as <code>-hda</code></li> <li>Running without <code>-initrd ...</code> and appending <code>init=/bin/sh</code> to the kernel command line</li> </ol> <p>Although you are not fully emulating the WR740N because most of the hardware is missing and it is a different kernel. Emulating a router in qemu is always going to be a partial process because of that.</p>
4480
2014-05-29T16:07:27.903
<p>I'm trying to emulate a TP-Link WR740N in Qemu (MIPS). I have extracted the <code>rootfs.img</code> from the firmware, and downloaded <code>vmlinux-2.6.32-5-4kc-malta</code> from here: <a href="http://people.debian.org/~aurel32/qemu/mips/" rel="noreferrer">http://people.debian.org/~aurel32/qemu/mips/</a>.</p> <p>Then, I started Qemu with these parameters:</p> <pre><code>qemu-system-mips -M malta -kernel 'vmlinux-2.6.32-5-4kc-malta' -hda 'rootfs.img' -append "root=/dev/sda1 console=tty0" -nographic </code></pre> <p>And it got stuck on:</p> <pre><code>[0.000000] console [tty0] enabled, bootconsole disabled </code></pre> <p>I've also tried to run it like this:</p> <pre><code>sudo qemu-system-mips -M malta -initrd 'rootfs.img' -kernel 'vmlinux-2.6.32-5-4kc-malta' -nographic -append "console=ttyS0,115200 root=/dev/sda rootfstype=jffs2 init=/sbin/init" -hda 'hda.img' </code></pre> <p>and I get this error:</p> <pre><code>[ 0.796000] sda: unknown partition table [ 0.808000] sd 0:0:0:0: [sda] Attached SCSI disk [ 0.812000] RAMDISK: squashfs filesystem found at block 0 [ 0.812000] RAMDISK: Loading 2556KiB [1 disk] into ram disk... done. [ 0.928000] VFS: Cannot open root device "sda" or unknown-block(8,0) [ 0.928000] Please append a correct "root=" boot option; here are the available partitions: [ 0.928000] 0800 65536 sda driver: sd [ 0.932000] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(8,0) </code></pre> <p>New try after answer from 6EQUJ5 [I still get the same error though (the second one)]:</p> <p>This is what I'm trying:</p> <pre><code>sudo qemu-system-mips -M malta -kernel 'vmlinux-2.6.32-5-4kc-malta' -nographic -append "init=/bin/sh" -hda 'myFileSystem.img' </code></pre> <p>And this is a link to download the filesystem I've created:</p> <pre><code>http://speedy.sh/vBUEQ/myFileSystem.img </code></pre> <p>Running "file" on my filesystem:</p> <pre><code>Linux rev 1.0 ext2 filesystem data (mounted or unclean), UUID=dac7072e-2c8b-408f-a080-57ea60cfd9ea </code></pre> <p>Those are the commands I've used to create it and move the files into it:</p> <pre><code>dd if=/dev/zero of=~/myFileSystem.img bs=1024 count=65536 mke2fs myFileSystem.img mkdir /mnt/virtual mount -o loop ~/myFileSystem.img /mnt/virtual </code></pre>
Emulate TP-LINK WR740N with QEMU
|firmware|qemu|mips|
<p>It's a lot of questions, here are a few answers:</p> <h2>How can we write something in memory with a format string vulnerability ?</h2> <p>For this, you need to know two specific features used in the <code>printf</code> format string specifications. First, <code>%n</code> is a format specifier that has the following effect (according to the manual page):</p> <blockquote> <p><code>%n</code> The number of characters written so far is stored into the integer indicated by the <code>int *</code> (or variant) pointer argument. No argument is converted.</p> </blockquote> <p>Now, the second format string feature will allow us to select a specific argument from the format string. The main selection operator is <code>$</code>, and the following code means that we select the second argument (here the outcome will be to display <code>2</code>):</p> <pre><code>printf("%2$x", 1, 2, 3) </code></pre> <p>But, in the general case, we can do <code>printf("%&lt;some number&gt;$x")</code> to select an arbitrary argument of the current <code>printf</code> function (format string argument does not count).</p> <p>If we could pass the string <code>AAAA%10$n</code> to the program and make it appear as a format string, then we could write the value <code>4</code> to the address <code>0x41414141</code>.</p> <p>So, format string bugs may offer a full access to the memory and you can decide what to write and where in the memory.</p> <p>I really advise you to read "<a href="http://crypto.stanford.edu/cs155/papers/formatstring-1.2.pdf">Exploiting Format String Vulnerabilities</a>" from Scut (2001) to get a whole grasp on these kind of manipulations.</p> <h2>Are they other languages than C/C++ that are vulnerable to these bugs ?</h2> <p>Well, format string bugs are tied up to the <code>printf</code> function family and the way format strings may be passed to the function. It's a whole class of security issue itself. So, you might find ways to exploit similar problems in some other languages. Though, you may not find the exact same features as the format string capabilities in other languages may differ a lot.</p> <p>I do think about languages such as Perl, Python, and so on, that all offer similar access to format string features.</p> <h2>How can I spot format string vulnerabilities if I have only the binary ?</h2> <p>First, you have to locate the calls to procedure of the <code>printf</code> family. Then, I would say that fuzz-testing (fuzzing) should be a good way to find the vulnerabilities. Especially if you can forge a few entries with seeds such as <code>AAAA%10$n</code>.</p> <p>If you want a more accurate and exhaustive way to find it, you will probably need to do some binary analysis and taint analysis on every call to a procedure of the <code>printf</code> family.</p>
4487
2014-05-30T15:31:43.500
<p>I think I understand how a format string vulnerability works, but what I have seen so far it can only be used to increase the value of an integer.</p> <p>Can format string vulnerability also be used to write anything else?</p> <p>And, by the way, are there languages, other then C and C++, that are at risk of creating such a vulnerability? How can I spot a format string vulnerability if I only have a binary?</p>
How can a format string vulnerability be used to write a specific string into memory?
|binary-analysis|c|c++|vulnerability-analysis|strings|
<p><a href="http://recon.cx/2012/schedule/events/236.en.html">This presentation</a> offers one approach.</p> <p>Title: Reverse engineering of binary programs for custom virtual machines</p> <p>Authors: Alexander Chernov and Katerina Troshina</p> <blockquote> <ul> <li>Initial markup of the binary program. Identification of data sections and code sections. Prior information about the purpose of the program or even some documentation hints may be used. At this step the entry point to the code (or several entry points) are identified. </li> <li>Reconstruction of subroutine structure by identification of the subroutine borders. The subroutine return (RET) instruction is identified. It is naturally to expect that the last instruction in the code segment would be the return instruction. RET instruction normally separates subroutines, so we may expect, that CALL instruction should pass the control right after RET instruction in many (or even most) cases. </li> <li>Identification of the unconditional jump (JMP) instruction using the assumption, that code execution starts at some fixed address. </li> <li>Identification of call instruction. Call instructions are similar to unconditional jumps. By investigation of initialization code several candidates for the CALL instruction can be identified, and the one candidate remained after validation on the whole code.</li> <li>Recovering of absolute and relative jumps and call by looking at the bit encoding of instruction and checking whether it could be an offset relative to the next instruction word. This way relative jumps, calls and candidates for conditional jumps were identified. </li> <li>Identification of memory load and store instruction by observing load-store patterns for memory-memory copy operations. </li> <li>Observations on the virtual machine register structure and register width. How many registers this VM probably has and how wide are they. </li> <li>Observations on the arithmetics and logics operation by pairing with the identified conditional jumps.</li> </ul> </blockquote>
4504
2014-06-02T13:54:38.543
<h1>Constraints:</h1> <p>I am doing reverse engineering of a binary firmware image of unknown provenance, which operates on a device that is <strong>not</strong> physically accessible to me. That is, I can't take apart the device, don't have even block diagrams for its function, and have no ability to identify the microprocessor by visual inspection or by asking the creator of the object. Literally the <em>only</em> thing available is the binary image.</p> <h1>The Question:</h1> <p>My question is: <strong>given those constraints</strong> what tools or theoretical approaches could be employed to identify the processor's instruction set by examining the binary?</p> <h1>Research so far:</h1> <p>I have, of course, attempted to use disassemblers for various popular ISAs such as ARM, x86 and MIPS. I have also done a literature search for research papers but haven't turned up anything at all.</p> <p>Ideally, what I'd like is a tool that would examine the binary and then report something like &quot;75% probability that this is code for a Renesas M16C.&quot;</p>
how can the processor instruction set be identified solely by examining a binary image?
|disassembly|machine-code|
<p>if you reverse the byte order, and assume signed numbers you get these triplets:</p> <pre><code>-2468488 976475 146741 732616 976475 146741 732616 976475 -1238346 -2468488 976475 -1238346 -2468488 -142759 146742 732616 -142759 146742 732616 -142759 -1238346 -2468488 -142759 -1238346 </code></pre> <p>these seem like the coordinates of the corners of a 3d cube </p> <pre><code>x=(-2468488 .. 732616) y=( -142759 .. 976475) z=(-1238346 .. 146742) </code></pre>
4513
2014-06-03T07:49:54.047
<p>I'm analyzing an rather ancient 3D mesh format (from 1995 or 1996). Inside the files, there are blocks of what I think are vertices.</p> <p>For example, the following is a direct hex dump from such a part:</p> <pre><code>7855DAFF 5BE60E00 353D0200 C82D0B00 5BE60E00 353D0200 C82D0B00 5BE60E00 B61AEDFF 7855DAFF 5BE60E00 B61AEDFF 7855DAFF 59D2FDFF 363D0200 C82D0B00 59D2FDFF 363D0200 C82D0B00 59D2FDFF B61AEDFF 7855DAFF 59D2FDFF B61AEDFF </code></pre> <p>These blocks are introduced by a little header, which has a value that could be the number of vertices that are present in the corresponding data block. For this excerpt, there is a <code>0x08</code>. Since we have 24 values of 32bit, I think it is safe to assume that these blocks are actual vertices (<code>0x08 * 3 = 24</code>, with <code>xyz</code>). Other headers also have this value and their data blocks also have the exact number of <code>dwords ([value in header] * 3 =&gt; number of dwords</code>).</p> <p>But, now I'm struggling at deciphering the number format that was used. It isn't IEEE754; a friend of mine also pointed out that the hardware that was used these days didn't perform well with floating-point numbers and therefore often fixed-point numbers where used.</p> <p>So, any idea what kind of format this could be ?</p>
Ancient number formats (probably fixed-point)
|binary-analysis|file-format|
<p>As an alternative to blabb's answer, if you'd like to set the environment variable via a GUI, you can use <a href="http://www.codeproject.com/Articles/32131/Dynamically-Add-Edit-Environment-Variables-of-Remo" rel="nofollow">http://www.codeproject.com/Articles/32131/Dynamically-Add-Edit-Environment-Variables-of-Remo</a></p>
4520
2014-06-04T10:43:36.750
<p>I am debugging a program that reads an environment variable. So far, I could not find how to launch it in Immunity/Olly with a custom environment.</p> <p>Anybody know how this can be done?</p>
Passing an environment to debugged program in Olly/Immunity
|ollydbg|immunity-debugger|
<p>The markings look like an Atmel part (it starts with "AT", which is common for Atmel parts). Given the size of the chip and context which you provided, I figured it was probably a serial EEPROM. Looking through Atmel's serial EEPROM datahsheets, your mystery chip is almost certainly an Atmel AT25128B-SSHL SPI EEPROM, which matches your chip's product markings and pinout.</p> <p>According to the AT25128B <a href="http://www.atmel.com/Images/doc8698.pdf">datasheet</a>, the first line should be ATHXXX, where XXX is a three digit date code. In your case, "ATH330" means it was made in the 30th week of 2013.</p> <p>The second line contains the product's truncated part number (truncated part numbers are used when the entire part number is too long to fit on the package) and country of assembly. The truncated part number for the AT25128B is "5DBL", which from the picture looks reasonably like what is printed on your chip, and the trailing "8" identifies the country of assembly (I don't know what country "8" corresponds to, but its probably somewhere in Asia :)).</p> <p>The last line is the Atmel lot number.</p>
4526
2014-06-04T16:43:28.923
<p>I'm working on reverse engineering a PCB (no documentation by manufacturer). I've identified all the other chips on this board but this one refuses to give up any google-able info. Are there any resources that can help me identify what kind of chip this is?</p> <p><a href="https://i.stack.imgur.com/mnUlS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UG05u.png" title="Hosted by imgur.com" /></a></p> <pre><code> ______________ D1 --|O ATH 330 |--? D2 --| |--Vss Vss--| 50?L 8 |--D4 GND--| 3U49758 |--D5 -------------- </code></pre> <p>D1, D2, D3 and D4 pins are connected to a 5x2 grid of test points which I've soldered a header into. Vss is connected to the Vss of a PIC32MX695F512H microcontroller.</p> <p>Let me know if I can provide additional info to assist this process.</p>
Identifying an unknown chip on a PCB
|hardware|embedded|pcb|
<p>There are no artifacts and surely the compiler, and I mean <code>GCC</code>, can generate a better and faster code if told so. The first version of your generated code is non optimized. Why ? Either because <code>-O0</code> flag (0 level optimizations ==> No optimizations) was specified, or because no optimization flags were specified and by default <code>GCC</code> turns optimizations off. </p> <p>Below you'll find two versions of the same code. Version 1 with <code>-O0</code> flag. Version 2 with <code>-O2</code> flag. </p> <ul> <li><p><strong>Version 1:</strong></p> <pre><code> 55 push rbp 48 89 e5 mov rbp,rsp 48 81 ec 10 04 00 00 sub rsp,0x410 89 bd fc fb ff ff mov DWORD PTR [rbp-0x404],edi 48 89 b5 f0 fb ff ff mov QWORD PTR [rbp-0x410],rsi 48 8b 85 f0 fb ff ff mov rax,QWORD PTR [rbp-0x410] 48 83 c0 08 add rax,0x8 48 8b 10 mov rdx,QWORD PTR [rax] 48 8d 85 00 fc ff ff lea rax,[rbp-0x400] 48 89 d6 mov rsi,rdx 48 89 c7 mov rdi,rax e8 40 fe ff ff call 400400 &lt;strcpy@plt&gt; 48 8d 85 00 fc ff ff lea rax,[rbp-0x400] 48 89 c7 mov rdi,rax e8 41 fe ff ff call 400410 &lt;puts@plt&gt; b8 00 00 00 00 mov eax,0x0 c9 leave c3 ret 66 2e 0f 1f 84 00 00 nop WORD PTR cs:[rax+rax*1+0x0] 00 00 00 </code></pre></li> <li><p><strong>Version 2:</strong></p> <pre><code> 48 81 ec 08 04 00 00 sub rsp,0x408 48 8b 76 08 mov rsi,QWORD PTR [rsi+0x8] 48 89 e7 mov rdi,rsp e8 ad ff ff ff call 400400 &lt;strcpy@plt&gt; 48 89 e7 mov rdi,rsp e8 b5 ff ff ff call 400410 &lt;puts@plt&gt; 31 c0 xor eax,eax 48 81 c4 08 04 00 00 add rsp,0x408 c3 ret 0f 1f 00 nop DWORD PTR [rax] </code></pre></li> </ul> <p>If you're interested in the optimizations performed by <code>GCC</code> you should read <a href="https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html">this</a> link, and <a href="https://gcc.gnu.org/onlinedocs/gcc-4.6.1/gnat_ugn_unw/Optimization-Levels.html">this</a> one too. You can also check the <a href="ftp://ftp.uvsq.fr/pub/gcc/summit/"><code>GCC</code> summit publications</a>.</p>
4532
2014-06-04T23:28:52.360
<p>So, say that I have the following code, which gives three examples of what I believe to be unnecessary copies of values.</p> <pre><code>mov QWORD PTR [rbp-0x18],rdi mov rdx,QWORD PTR [rbp-0x18] lea rax,[rbp-0x10] mov rsi,rdx mov rdi,rax call 4003e0 &lt;strcpy@plt&gt; </code></pre> <p>Why is the value in <code>rdi</code> copied to memory at <code>rbp-0x18</code>, then copied back to <code>rdx</code> ? It's then copied to <code>rsi</code> (2 extra copies).</p> <p>Finally, why the <code>lea + mov</code> for <code>rbp-0x10</code> to <code>rax</code>, then to <code>rdi</code> ? Is there any reason the following code wasn't generated ?</p> <pre><code>mov rsi,rdi lea rdi,[rbp-0x10] call 4003e0 &lt;strcpy@plt&gt; </code></pre> <p>(My guess is that this is just an artifact of the code generation in the compiler, but I'm making sure there's not some rules of x86-64 that I'm missing.)</p>
Why are values passed through useless copies?
|linux|x86-64|
<p>Page 4 of <a href="https://www.nccgroup.com/media/190706/usb_driver_vulnerabilities_whitepaper_january_2013.pdf" rel="nofollow">https://www.nccgroup.com/media/190706/usb_driver_vulnerabilities_whitepaper_january_2013.pdf</a> gives a good introduction to setting up a USB-fuzzing test platform.</p> <blockquote> <p>Testing USB drivers on host machines is not a straightforward process, because you either need to emulate a USB device or proxy the traffic between a device and the host. As a result of how the protocol works it would be extremely difficult to convert a USB host e.g. a PC into a USB device and therefore, if you are not modifying the traffic en-route via some kind of hooking or proxy solution, you need to use a hardware-based approach. This section details the various different approaches to testing USB hosts and compares the relative merits of each...</p> </blockquote>
4536
2014-06-05T07:56:14.460
<p>I would like to analyze (and fuzz) a USB device and I need a bit of guidance to setup a full platform to discuss with the device.</p> <p>First, I would like to know what are the most used hardware cards to emulate and perform fuzzing on USB devices. I've heard about the <a href="http://goodfet.sourceforge.net/hardware/facedancer11/">FaceDancer11 card</a> with a Python API (see a few blog posts [<a href="http://travisgoodspeed.blogspot.fr/2012/07/emulating-usb-devices-with-python.html">1</a>,<a href="http://travisgoodspeed.blogspot.fr/2012/10/emulating-usb-dfu-to-capture-firmware.html">2</a>] from <a href="http://travisgoodspeed.blogspot.fr/">Travis Goodspeed</a>). But, are they others ?</p> <p>Also, if someone could come with a list of the needed hardware devices and, maybe, some existing Python libraries that are useful to have and, what development effort is needed to setup such a platform, it would be helpful.</p>
Setting an USB Emulation and Fuzzing Platform?
|hardware|fuzzing|usb|
<p>This is a million dollar question and I doubt anybody will be able to provide a convincing answer. There are many methods used by antivirus software &amp; analysts. </p> <p>One is to perform a stupid matching with known malware signatures. Another could be to statically analyze the application, extract the control flow (by reconstructing the <a href="https://en.wikipedia.org/wiki/Control_flow_graph" rel="nofollow"><code>CFG</code></a>) of the application and deploy heuristics &amp; pattern matching algorithms in order to determine if the application performs suspicious tasks. This can usually be done after analyzing known malware &amp; building profiles of their behaviors (suspicious <code>syscall</code> call graph, ...). </p> <p>There are numerous techniques and this field is still open for research (<a href="http://www.cs.colostate.edu/~anderson/cs545/assignments/solutionsGoodExamples/assignment8Williams.pdf" rel="nofollow">this</a> document describes an interesting one), some are extremely advanced and may necessitate sharp mathematical skills, and others are hard to program. Mainly, because none of them follow the standard algorithmic approach and rather use machine learning, genetic algorithms, and sometimes <code>AI</code>. </p> <p>I suggest you going through <a href="http://www.securelist.com/en/analysis/204791972/The_evolution_of_technologies_used_to_detect_malicious_code?print_mode=1" rel="nofollow">this</a> <code>Securelist</code> article, and <a href="http://virii.es/U/Using%20Entropy%20Analysis%20to%20Find%20Encrypted%20and%20Packed%20Malware.pdf" rel="nofollow">this</a> publication too if you're interested by more material. </p>
4546
2014-06-05T13:33:02.397
<p>How should I decide file is malware or not. Before reverse engineering any file, I should be suspect the file. What are the various ways to decide if exe is malicious? </p> <p>Thanks </p>
How to decide file is malware or not?
|malware|
<p>I do not know your exact case. But if the binary is just stripped (or sstrip is used) and your function is just a call to an external symbol of a dynamic library, you might want to take a look at this little IDA python script of mine: <a href="http://h4des.org/blog/index.php?/archives/343-Restoring-external-symbol-calls-in-IDA-when-ELF-sections-are-deleted.html" rel="nofollow">http://h4des.org/blog/index.php?/archives/343-Restoring-external-symbol-calls-in-IDA-when-ELF-sections-are-deleted.html</a></p> <p>This script uses an ELF parser library I wrote (called ZwoELF) that tries to only use information that the ELF loader is using to circumvent problems that almost all analysis tools/frameworks I tested have because they rely on optional data like ELF sections.</p>
4549
2014-06-05T14:22:49.187
<p>I would like to load a function I have decompiled in IDA Pro. All I have is the IDA Pro function name <code>sub_xxxx()</code> and obviously the address. I had thought about using <code>dlopen</code> to load the binary but obviously I don't have a symbol to load as the binary has been stripped. Could I somehow call the function without a symbol table? Or do I have to rebuild the symbol table of the binary to then use <code>dlsym</code> to locate and load the symbol?</p>
Rebuild symbol table
|disassembly|dynamic-linking|
<p>I've just checked the linux kernel loading ELF function (loading_elf_binary) and I find out that if <strong>e_phnum > (65536U / sizeof(struct elf_phdr))</strong> or <strong>e_phnum &lt; 1</strong>, the current loading routine will stop (line 613-615), the ELF file won't be loaded:</p> <pre><code>610 /* Now read in all of the header information */ 611 if (loc-&gt;elf_ex.e_phentsize != sizeof(struct elf_phdr)) 612 goto out; 613 if (loc-&gt;elf_ex.e_phnum &lt; 1 || 614 loc-&gt;elf_ex.e_phnum &gt; 65536U / sizeof(struct elf_phdr)) 615 goto out; 616 size = loc-&gt;elf_ex.e_phnum * sizeof(struct elf_phdr); 617 retval = -ENOMEM; 618 elf_phdata = kmalloc(size, GFP_KERNEL); 619 if (!elf_phdata) 620 goto out; </code></pre> <p>Reference: <a href="http://lxr.free-electrons.com/source/fs/binfmt_elf.c" rel="nofollow">http://lxr.free-electrons.com/source/fs/binfmt_elf.c</a></p> <p>Also the number of programheader (e_phnum) in ELF32/64 is always 16 bit variable</p> <pre><code>203 typedef struct elf32_hdr{ 204 unsigned char e_ident[EI_NIDENT]; 205 Elf32_Half e_type; 206 Elf32_Half e_machine; 207 Elf32_Word e_version; 208 Elf32_Addr e_entry; /* Entry point */ 209 Elf32_Off e_phoff; 210 Elf32_Off e_shoff; 211 Elf32_Word e_flags; 212 Elf32_Half e_ehsize; 213 Elf32_Half e_phentsize; 214 Elf32_Half e_phnum; 215 Elf32_Half e_shentsize; 216 Elf32_Half e_shnum; 217 Elf32_Half e_shstrndx; 218 } Elf32_Ehdr; 219 220 typedef struct elf64_hdr { 221 unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */ 222 Elf64_Half e_type; 223 Elf64_Half e_machine; 224 Elf64_Word e_version; 225 Elf64_Addr e_entry; /* Entry point virtual address */ 226 Elf64_Off e_phoff; /* Program header table file offset */ 227 Elf64_Off e_shoff; /* Section header table file offset */ 228 Elf64_Word e_flags; 229 Elf64_Half e_ehsize; 230 Elf64_Half e_phentsize; 231 Elf64_Half e_phnum; 232 Elf64_Half e_shentsize; 233 Elf64_Half e_shnum; 234 Elf64_Half e_shstrndx; 235 } Elf64_Ehdr; </code></pre> <p>Define data type as followed:</p> <pre><code>9 typedef __u16 Elf32_Half; 16 typedef __u16 Elf64_Half; </code></pre> <p>Reference: <a href="http://lxr.free-electrons.com/source/include/uapi/linux/elf.h#L263" rel="nofollow">http://lxr.free-electrons.com/source/include/uapi/linux/elf.h#L263</a></p> <p>So, also in the case of a invalid value of e_phnum (invalid ELF file), the maximum value of e_phnum is 65535.</p> <p>Hope this helpful!</p>
4551
2014-06-06T03:23:17.553
<p>I recently read that the kernel and the dynamic loader mostly deal with the <code>program header tables</code> in an ELF file and that assemblers, compilers and linkers deal with the <code>section header tables</code>.</p> <p>The number of program header tables and section header tables are mentioned in the ELF header in fields named <code>e_phnum</code> and <code>e_shnum</code> respectively. <code>e_phnum</code> is two bytes in size, so if the number of program headers is > 65535, we use a scheme known as <code>extended numbering</code> where, <code>e_phnum</code> is set to 0xffff and <code>sh_link</code> field of the zeroth section header table holds the actual count.</p> <p>My doubt is :</p> <blockquote> <p>If the count of program headers exceeds 65535, does that mean the kernel and/or the dynamic loader end up having to read the section table ?</p> </blockquote>
Kernel dealing with the section headers in an ELF
|linux|file-format|elf|kernel-mode|
<p>I have played with at least one (not a D-Link) Linux-based router that stored its configuration in a bare <code>mtd</code> partition and accessed it using a proprietary binary. It compressed the data using LZMA or something but within that, you could see passwords in clear-text (not good!)</p> <p>D-Link actually have a very good GPL source code system, go to <a href="http://tsd.dlink.com.tw/downloads2008list.asp?SourceType=download&amp;OS=GPL" rel="nofollow">http://tsd.dlink.com.tw/downloads2008list.asp?SourceType=download&amp;OS=GPL</a> and type in 2760 and you can download the entire buildroot and source for that router.</p> <p>Even if they happen to use some non-standard proprietary mechanism for saving configuration, you should be able to get some idea of where it is hidden from examining the GPL sources...</p>
4552
2014-06-06T09:30:42.100
<p>I'm currently researching my home router (D-Link 2760-U) which has a (kind-of) proprietary ISP firmware. What I'm trying to achieve is understanding how the router is persisting it's configuration settings across reboots.</p> <p><code>mount</code> output:</p> <pre><code>/dev/mtdblock0 on / type squashfs (ro,relatime) /proc on /proc type proc (rw,relatime) tmpfs on /var type tmpfs (rw,relatime,size=420k) tmpfs on /mnt type tmpfs (rw,relatime,size=16k) sysfs on /sys type sysfs (rw,relatime) </code></pre> <p>I did <code>nvram show</code> and it does contain some wireless configuration such as the encryption in use, wireless modes, pre-shared key but that's about it. Obviously the router has other configurations (such as DNS, PPP, Port forwards etc) that must be stored elsewhere. As it can be observed, all mounted filesystems are volatile and thus configuration cannot be stored in them.</p> <p>Where can the information be saved besides filesystem and NVRAM? How do I go about finding this out?</p>
How can I figure where my router stores it's configuration across reboots?
|linux|firmware|embedded|
<p>The file begins:</p> <pre><code>0000000: 4148 3030 4938 e66c 000e aa28 9835 0589 AH00I8.l...(.5.. 0000010: 3004 125a 1b39 65ff 47e4 b95c 0001 0014 0..Z.9e.G..\.... 0000020: 5531 3248 3036 3454 3030 5f4e 4554 4745 U12H064T00_NETGE 0000030: 4152 0000 AR.. </code></pre> <p>The reason for picking this size will soon become clear.</p> <p>The first four bytes (<code>AH00</code>) are probably file magic. Googling just that string brings up <a href="http://www.0xf8.org/2009/07/hacking-the-netgear-wg102-access-point/" rel="nofollow">this page</a>, which has a detailed breakdown of a different firmware file with a similar structure.</p> <p>The next four bytes are not described by the linked page. Reading them as a 32-bit big-endian value (BE32), though, you get 0x4938e66c = 1228465772, which is plausibly a recent UNIX timestamp (usually values from around 800,000,000 to 1,500,000,000). Indeed, it decodes to <code>Fri Dec 5 08:29:32 2008 GMT</code>, which is plausibly the build date of the hardware (and I note that the linked article has 0x481ac265 = <code>Fri May 2 07:27:33 2008 GMT</code>, which also seems plausible).</p> <p>The next four bytes read as a BE32 value give 961064. The total filesize is 961116 bytes, so this is likely the payload size, leaving 52 bytes for the header (and thus explaining why I chose to show the first 52 bytes here).</p> <p>The next 32 bytes are the MD5 sum of the payload as indicated by the linked page. I deleted the first 52 bytes and MD5 summed the result:</p> <pre><code>983505893004125a1b3965ff47e4b95c /tmp/fw.sqz </code></pre> <p>which is exactly what the header contains.</p> <p>The next two bytes are unknown.</p> <p>The next two bytes are 0x0014, which is the length of the string that follows (including two padding NULs). While I'm not familiar with Netgear routers, I'm guessing this is a model/revision number for the hardware target.</p> <p>And there you go: that's the <code>.chk</code> file header.</p> <pre><code>char magic[4]; uint32_t timestamp; // UNIX timestamp uint32_t payload_size; char md5sum[32]; uint16_t unknown; // = 1 on all files seen so far uint16_t model_size; char model[model_size]; </code></pre> <hr> <p>In the original linked page, the payload was a plain ELF file. Unfortunately, in your firmware, the payload is some other kind of file, with the magic <code>sqz</code> ("squeeze"?). It's clearly compressed, but I can't tell what it's compressed with. For now, this will have to be an incomplete answer until someone figures out what the compression format is.</p>
4565
2014-06-08T17:40:55.190
<p>Note: I'm aware of the technical and legal implications of reverse-enginneering binaries.</p> <p>I have the firmware for a Netgear WGR614v7 router, in the form of a .chk file, coming from Netgear themselves, and I wish to unpack the file. My understanding is that a firmware .chk file is <a href="http://www.dd-wrt.com/wiki/index.php/WGR614_v8" rel="nofollow">a header</a> before a TRX image, and I've tried to untrx the ile I had sans header, or with header as well. Neither that nor <code>binwalk</code> succeeded. Two useful strings are seen very close to the beginning of the file:</p> <ul> <li>AH00I8</li> <li>U12H064T00_NETGEAR</li> </ul> <p>Inspecting the file in a hex editor, I'm unable to find the <a href="http://wiki.openwrt.org/doc/techref/header?s%5b%5d=trx" rel="nofollow">TRX file signature</a> (I was looking for ASCII <code>HDR0</code>). I also cannot find any sort of compression magic values, except fairly far into the file where they're not likely to signify the beginning of the actual content I'm looking for. </p> <p>Am I looking for the wrong filetypes? Is anything about this structure known that I haven't found yet?</p> <p><strong>Edit:</strong> The firmware has been downloaded from <a href="http://support.netgear.com/product/WGR614v7" rel="nofollow">Netgear's site</a>. I tried chopping off various lengths but cannot find a reasonably-located compression or TRX header. The characteristic <code>ff ff ff ff</code> of IMG images used as a method of preventing a repetitive boot firmware is also not existent.</p> <p><strong>Edit 2:</strong> I did some searching of my own, and found a <a href="http://ttf.mine.nu/techdocs.htm" rel="nofollow">decompression utility</a>. When I chopped the file such that <code>sqz</code> had been the first characters, that utility seemed to find valid Huffman structures but incur a size mismatch. A result of the decompression yielded 11 bytes, while the program warned me:</p> <blockquote> <pre><code>Warning: Unpacked file should be 7537274 bytes but is 396409921 bytes! at ./unpack.pl line 61, &lt;STDIN&gt; line 3. </code></pre> </blockquote> <p>Of course, it could be that many kinds of data that is corrupt might be partially readable as huffman giving me strange results as seen here.</p>
Format of .chk firmware package on WGR614v7
|file-format|firmware|
<p>Some time ago I wrote <a href="https://github.com/ea/minblox" rel="nofollow">minblox</a> for that exact purpose. It relies on DynamoRIO. Compared to minset which uses pin tool, there isn't much of a difference. Tho I think actual set minimization part works faster than minset. </p> <p>Minblox tool is comprised of two parts.</p> <ul> <li>A DynamoRIO instrumentation part (libbbcoverage) tasked with recording all basic block executed during application execution.</li> <li>minblox.py - Python script that runs the DynamoRIO instrumentation and analyzes the log files to minimize the sample set.</li> </ul> <p>Though, do bear in mind that I've only tested this for a specific case I needed it, so your mileage might vary. </p>
4568
2014-06-08T20:49:34.820
<p>Anyone know of any tools or scripts that can help in <a href="http://googleonlinesecurity.blogspot.de/2011/08/fuzzing-at-scale.html" rel="nofollow">corpus distillation</a> ? I know of <a href="http://old.peachfuzzer.com/v3/minset.html" rel="nofollow">Peach Minset</a>, but not other than that. Appreciate if anyone could share.</p>
Corpus Distillation
|tools|fuzzing|
<p>IDA can only work with one IDB at a time. You'll need to either work with all modules in one IDB, or use serveral IDBs/IDA instances and detach/attach to the process as necessary.</p>
4581
2014-06-10T09:36:23.317
<p>I can't seem to figure out if I can and how you load multiple idb files with notes into a debugging session?</p> <p>Is there a method or plugin that allows me to load these idb's? What I am doing now is start the program make a memory snapshot and make notes that way. When I start the new debuggin session I rebase the dlls. </p> <p>This does really not work well ;)</p> <p>note, I currently only have IDA Basic.</p>
Loading multiple IDB files for debugging session
|ida|
<p>Alternatively, you can select an address and press <code>ctrl + *</code> (use the <code>*</code> at the right pad)</p>
4604
2014-06-13T09:05:00.727
<p>I just was playing around with Windbg, debugging some application. At some point I had to manipulate EIP which was pretty easy in Windbg. But then once I switched back to Immunity, I could not figure out how to do the same thing.</p> <p>Is there some way you can change the EIP inside Immunity?</p>
Manipulate EIP in Immunity Debugger
|windbg|immunity-debugger|
<p>FYI, the injection method to which you're referring is called <strong>dynamic forking</strong> or <strong>process hollowing</strong>.</p> <p>When you attach to the child process with OllyDbg, OllyDbg will create a new thread for itself, but the main thread (the one that would have been resumed with <code>NtResumeThread()</code> from the parent) will still be suspended. Once you've attached with OllyDbg, you can set a breakpoint on the OEP and resume the suspended thread; this will cause OllyDbg to then break at the OEP.</p>
4607
2014-06-13T17:10:27.290
<p>When analyzing malware, I come across packers that inject the actual malware code into a newly spawned process and execute it that way. For that, they create a process in suspended state, inject the code and resume it using <code>ntdll.NtResumeThread</code> on Windows.</p> <p>I would like to attach to the suspended process after the injection is done, to dump the memory and get the unpacked binary. For that, I break at <code>ntdll.NtResumeThread</code>. Using Olly 2, I can attach to the suspended process.</p> <p>My problem is now that this seems to resume the process. That would be okay if it would break at the entry point. But it doesn't. Olly does not break until the process I attached to has terminated. Yes, I can dump the memory then. But only if it was not modified by the malware. Also, I don't want the malware code to run at all during unpacking.</p> <p>So, is there a way to make Olly break (reliably) at the entry point of the new process?</p> <p>Thanks in advance!</p>
Ollydbg 2: Breaking after attaching to a suspended process
|ollydbg|
<p>Sorry, I can't post this as a comment but a couple of quick (and non-exhaustive) tests show the following:</p> <ul> <li>gcc (4.6.3) uses <code>or</code> instead of <code>mov</code> when optimising for size (<code>/Os</code>)</li> <li>msvc (13) uses <code>or</code> instead of <code>mov</code> whatever the optimisation setting (including disabled)</li> <li>clang (3.0) uses <code>mov</code> whatever the optimisation setting</li> </ul> <p>gcc's behaviour, in particular, supports Peter Andersson's answer.</p>
4609
2014-06-13T19:03:42.253
<p>I have read the assembly line </p> <pre><code>OR EAX, 0xFFFFFFFF </code></pre> <p>and in the register <code>EAX</code> the program has stored a string. I have problems to understand how we can make a comparison with a string and a value like that. After performing that instruction, <code>EAX</code> has the value <code>0xFFFFFFFF</code>.</p> <p>Can someone tell me which purpose that operation has ? Is it a line which comes frequently in an assembly code ? (for example the line <code>XOR EAX, EAX</code> which is an efficient way to make <code>EAX = 0</code> ? Is it something like that ?)</p>
Purpose of OR EAX,0xFFFFFFFF
|assembly|
<p>I ran the installer through an online EXE inspector which told me the <code>102</code> resource contained <em>LZMA compressed data</em>. <sup>Stupidly, I closed that window to look up what 'LZMA' is. I forgot to note the URL of this specific tool, and now I cannot find it anymore! Such a shame because this hint was <em>crucial</em>.</sup></p> <p>I then ran it through <a href="http://pedump.me" rel="nofollow">PEdump.me</a>, which allows one to download it separately. To unpack the LZMA compression, I used Stuffit Expander (for OS X), but you can probably use 7-Zip as well -- you may need to add the file extension <code>.lzma</code> to make it work.</p> <p>This gave me a <em>TAR-like</em> file, containing a few more executables. My local <code>tar</code> was unable to unpack it any further (possibly it's some variant of the standard <code>tar</code>).</p> <p>The TAR file format is a wrapper to concatenate multiple files into one; its headers contain the original file name and its size, amongst other data. TAR does <em>not</em> apply compression to the resulting file, so you only need a good hex editor to manually split it into the separate programs.</p> <hr> <blockquote> <p>.. my very questionable use of 7-zip for this purpose which also fails for a large number of executables ..</p> </blockquote> <p>Being able to show the <a href="http://msdn.microsoft.com/en-us/magazine/cc301805.aspx" rel="nofollow">PE Sections</a> of a Windows executable is a rather uncommon function for a general compressing/uncompressing program... That said: I have found no fault in 7-zip's handling of PE executables. It splits them up into their sections and does nothing more.</p> <p>You can use a tool such as PE Studio to <em>inspect</em> the resources (are you sure it cannot extract them? It seems such a basic function); but after extracting them, you are on your own. There is no "standard" way of compressing or otherwise obfuscating resources; some programs may even contain custom code to extract their own data.</p> <p>Recognizing the format of a resource is then reduced to the more general "recognize the file format", which is an extremely broad topic on its own.</p>
4618
2014-06-16T12:05:49.690
<p>I'm trying to extract the files from the <a href="https://support.google.com/installer/answer/126299?hl=en" rel="noreferrer">Google Chrome offline installer</a> as a reverse engineering exercise</p> <p>So I tried extracting the data inside the installer PE. I tried pestudio which showed me two large embedded resources, however, pestudio had no option to dump them. Extracting the PE with 7-zip shows a file with the name <code>~102</code>.</p> <p>However, 7zip cannot make out anything out of the <code>~102</code> file. Viewing this file with a hex editor shows that it is a tar archive with around 20 bytes of additional info prepended to it. Removing these 20 bytes does not make it extractable, however.</p> <p>How can I extract the files from the binary?</p> <p>I'm a complete noob in reverse engineering, so please correct my mistakes instead of downvoting my question. I'd also be grateful if someone can tell me of a tool which can extract such data from PE executables (instead of my very questionable use of 7-zip for this purpose which also fails for a large number of executables).</p>
Extracting files from google chrome offline installer
|static-analysis|pe|
<p>There are many ways, but I'll cite two. Usually, a binary file, if not stripped, contains symbols (function names, variable names, ...). These symbols are usually used to ease debugging and are stored using a certain format, DWARF for example.</p> <p>The first method is to disassemble the binary and look for specific threading libraries related symbols. For example : </p> <pre><code> objdump -D ./YOUR_PROGRAM | grep -i thread </code></pre> <p>The second one is to hijack the threading library function calls using your own library and <strong>LD_PRELOAD</strong>. The concept is fairly simple, you write a library (.so) in which you implement the functions which you want to check for, let's say <strong>pthread_create</strong> or <strong>pthread_join</strong>, and reimplement it this way :</p> <pre><code> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) { int ret; static void *(*ext_pthread_create)(pthread *, const pthread_attr_t *, void *, void *); ext_pthread_create = dlsym("RTLD_NEXT", pthread_create); ret = ext_pthread_create(thread, attr, start_routine, arg); printf("pthread_create called !\n"); return ret; } </code></pre> <p>All you have to do after compiling and testing your library is call yor program this way :</p> <pre><code> LD_PRELOAD=hooklib.so ./YOUR_PROGRAM PARAMS </code></pre> <p>If the function is called, you'll see the printf message on the standard output. </p>
4623
2014-06-16T23:19:11.793
<p>Is it possible to determine if a binary (static or shared and not stripped) is compiled with Linuxthreads or NPTL implementation ? </p>
How to determine which thread implementation binary compiled with
|linux|elf|libraries|
<p>There is already an answer by the creator of frida, but I just wanted to add that, specifically, we can use the convenience tool <code>frida-trace</code> with a .so file, e.g.</p> <pre><code>frida-trace -Ui 'nameOfYourLib.so!*' -p &lt;PID&gt; </code></pre> <p>to dynamically see what's getting called (entry and exit moments) in that .so file during runtime as you run the app normally (it will filter out to trace only functions within nameOfYourLib.so). This could, for example, be used in conjunction with a static disassembler to find interesting functions to explore deeper.</p>
4624
2014-06-17T07:09:58.757
<p>I know how to reverse-engineer normal Android APKs using tools like <code>apktool</code> and <code>dex2jar</code>, but I don't know how to work with obfuscation.</p> <p>When I extract everything from APK, I get some Smali files (I tried JD-GUI, but the strings contained random names. Probably obfuscated using ProGuard.), some resource files, and a &quot;.so&quot; files in the <code>/lib</code> directory.</p> <ul> <li>How do I analyze the &quot;.so&quot; file? I know that SO files are kind of DLLs of the Linux world, but what are the tools that can be used to analyze SO files? Any links to videos would be very helpful.</li> <li>Also, how would I get around if there were a JAR file instead of an SO file in the APK?</li> </ul> <p>I know this largely constitutes learning by myself, but I really don't know what to look or where to look. Some examples would be really helpful. Thanks!</p>
How do I reverse-engineer .so files found in Android APKs?
|disassembly|binary-analysis|obfuscation|android|deobfuscation|
<p><code>dword ptr [val]</code> is exactly, what it says: <strong>A 32bit pointer to value</strong>. As to how <code>cmp</code>, <code>je</code> and all the other instructions work, I recommend the reading of the <a href="http://www.intel.com/Assets/en_US/PDF/manual/253666.pdf" rel="nofollow">Intel Manual</a>.</p>
4626
2014-06-17T10:30:17.550
<p>Right now I am playing around with a little <em>training</em> application I found on <a href="http://opensecuritytraining.info/" rel="nofollow">OpenSecurityTraining</a>. </p> <p>So, I analyzed this code and I think I understand this pretty well. The only thing I don't get is the <code>cmp</code> and <code>je</code> at lines <code>0x004010e3</code> and <code>0x004010e7</code> which seem to be some <code>if</code> conditions. But, I cannot figure out which condition should be met to take the jump instruction. </p> <p>My workaround was to manipulate <code>eip</code> when the <code>cmp</code> line was executed. But, my question is what condition has to be set to take the <code>je</code> instruction ? </p> <pre><code>004010e0 55 push ebp 004010e1 8bec mov ebp,esp 004010e3 837d0803 cmp dword ptr [ebp+8],3 004010e7 7412 je mystery!main+0x1b (004010fb) 004010e9 6834404200 push offset mystery!__rtc_tzz &lt;PERF&gt; (mystery+0x24034) (00424034) 004010ee e81c040000 call mystery!printf (0040150f) 004010f3 83c404 add esp,4 004010f6 83c8ff or eax,0FFFFFFFFh 004010f9 eb0b jmp mystery!main+0x26 (00401106) 004010fb e80affffff call mystery!mystery_function+0xffffffff`ffffffea (0040100a) 00401100 eb02 jmp mystery!main+0x24 (00401104) 00401102 eb02 jmp mystery!main+0x26 (00401106) 00401104 33c0 xor eax,eax 00401106 5d pop ebp 00401107 c3 ret </code></pre>
Which condition has to be met to execute this if branch
|disassembly|assembly|debuggers|windbg|
<p>For this you'd first need to realize how programs are recognized to be specific types of software.</p> <p>This can be specific imports, strings or binary strings within the code. When you realize how tools make these signatures try to be cunning and put the signature in your 'malicious' application. Check it with your 'signature' tooling and tweak if required.</p>
4633
2014-06-18T15:49:11.293
<p>I'm looking for a way to recognize an executable file as a NullSoft installer. I´m trying to prove that a malicious software is capable of changing the PE signature so we can not trust in some tool tell us a PE is a NullSoft Installer only because it have found the NullSoft signature. </p> <p>Any help will be appreciated, recommended tools, etc ...</p> <p><strong>EDIT</strong></p> <p>After reading the Stolas's answer I decided to edit the question and add more info.</p> <p>I already tried with to use an hex editor on an original NullSoft installer and I searched for the string <code>NullSoft</code> this yielded the following result:</p> <p><img src="https://i.stack.imgur.com/UJMrQ.png" alt="Result for searching the string &quot;Nullsoft&quot; with UltrEedit."></p> <p>The string was found in a <code>XML</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="Nullsoft.NSIS.exehead" type="win32"/&gt; &lt;description&gt; Nullsoft Install System v2.46 &lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"&gt; &lt;security&gt; &lt;requestedPrivileges&gt; &lt;requestedExecutionLevel level="requireAdministrator" uiAccess="false"/&gt; &lt;/requestedPrivileges&gt; &lt;/security&gt; &lt;/trustInfo&gt; &lt;compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"&gt; &lt;application&gt; &lt;supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/&gt; &lt;supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/&gt; &lt;/application&gt; &lt;/compatibility&gt; &lt;/assembly&gt; </code></pre> <p>These seems to be what I want to insert in my "malicious" app. So, how can I add that into my app? </p> <p>My app it's just a "Hello world" written in Visual C++.</p> <p>I'm aware that I have to write this at the same offset that in the original, but I just don't know how.</p>
How to change PE signature?
|malware|binary-analysis|pe|
<p>I would like to add the following definition to avoid any doubts:</p> <blockquote> <p>Decompilers are different from disassemblers in one very important aspect. While both generate human readable text, <strong>decompilers generate much higher level text, which is more concise and much easier to read</strong>.</p> </blockquote> <p>Excerpted from <a href="https://www.hex-rays.com/files/decomp_disasm.pdf" rel="nofollow noreferrer">official hex-rays doc</a></p> <p>Conclusion, the decompilers alleviate both problems compared to disassemblers: their output is shorter and less repetitive.</p>
4635
2014-06-18T19:06:56.220
<p>I have heard of disassemblers like IDA and debuggers like OllyDbg but honestly, when you give both of them a binary file it gives me the assembly code. I know that the decompiler gives the source code if you provide it a binary. However, I don't know how they differ in terms of mode of operationand I ask myself questions like "Why can a android/python code be decompiled but a C code be only disassembled?"</p> <p>Can anyone give a precise difference between these 3 kinds of tools?</p>
What's the difference between a disassembler, debugger and decompiler?
|disassembly|decompilation|binary-analysis|debuggers|
<p>The comment of Guntram Blohm is right. The original value of <code>i</code> is stored into <code>ecx</code> for a possible later use.</p> <p><a href="http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf" rel="nofollow">ISO/IEC 9899:TC3</a> (C99) --- 6.5.2.4 Postfix increment and decrement operators:</p> <blockquote> <p>The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.</p> </blockquote> <p>The sequence points are described in Annex C of the document.</p> <p>TCC performs only few optimizations, the code is generated in a single pass and every C statement is compiled on its own. It seems that the compiler is almost as simple as possible so it does not store any state during the compilation if it is not necessary.</p> <p>When TCC encountered the sequence point before <code>++</code> it did not know about the <code>++</code> operation. Performing the side-effect of the <code>++</code> operator later after evaluating the <code>++</code> operation would mean to store a state information. It seems that the author of TCC selected the simplest approach - to perform the side-effect together with the evaluation of the <code>++</code> operator.</p> <p>The original value of the <code>i</code> variable (before incrementing) can possibly be used again in the same expression so it is saved to the <code>ecx</code> register and the result of the postfix increment operation is stored to the variable on the stack immediately (<code>mov [ebp+var_4], eax</code>). It does not matter that the value in <code>ecx</code> is not used later. This is the disadvantage due to the simplicity of TCC. For example you can notice that the code loads the value of <code>i</code> from stack to <code>eax</code> even if the value is in <code>eax</code> already.</p> <p>Example of code which additionally uses the original value of <code>i</code>:</p> <pre><code>j = i++ + i * 3; </code></pre> <p>The assembly code:</p> <pre><code>13: 8b 45 fc mov eax, DWORD PTR [rbp-0x4] // load i to eax 16: 48 89 c1 mov ecx, eax // store the original value of i for later use 19: 83 c0 01 add eax, 0x1 // increment the value (the side effect of ++) 1c: 89 45 fc mov DWORD PTR [rbp-0x4], eax // store it to i - everything between "=" and "+" is done at this point including the side-effect of i++ 1f: 8b 45 fc mov eax, DWORD PTR [rbp-0x4] // load i to eax (Now it is the incremented value.) 22: ba 03 00 00 00 mov edx, 0x3 // load value 3 for the multiplication 27: 0f af c2 imul eax, edx // multiply 2a: 01 c1 add ecx, eax // add the original value of i (the result of i++) 2c: 89 4d f8 mov DWORD PTR [rbp-0x8], ecx // store the result to j </code></pre> <p>At <code>1f</code> the incremented value of <code>i</code> is being used but it is also possible to use the original value of <code>i</code> there and still be in adherence with C99 because the sequence point after <code>i++</code> was not encountered yet. In this case the sequence points are right before and after the statement.</p>
4641
2014-06-19T20:23:29.313
<p>Here's code that performs some arithmetics.</p> <pre><code>int main(void) { int i = 3; i++; i+= 2; return 0; } </code></pre> <p>I compiled it using 32-bit <a href="http://bellard.org/tcc/" rel="nofollow"><code>tcc</code></a> with the following command</p> <pre><code>tcc -o hello.exe hello.c </code></pre> <p>I, then, disassembled it using <a href="https://www.hex-rays.com/products/ida/support/download_freeware.shtml" rel="nofollow">IDA free edition</a>, and after some time staring at the <code>start</code> of the instructions I realized that the main function that I was looking for is in a subroutine, and going there I see this:</p> <pre><code>sub_401000 proc near var_4= dword ptr -4 push ebp mov ebp, esp sub esp, 4 // allocate 4 bytes on the stack for var i nop mov eax, 3 // i = 3 instructions mov [ebp+var_4], eax // mov eax, [ebp+var_4] // i++ instructions mov ecx, eax // inc eax // mov [ebp+var_4], eax // mov eax, [ebp+var_4] // i+=2 instructions add eax, 2 // mov [ebp+var_4], eax // mov eax, 0 jmp $+5 leave retn sub_401000 endp </code></pre> <p>I've added my understanding of what's going on in comments on the right for the body of the method that I am interested in.</p> <p>For example, incrementing the variable would involve moving a value onto a register and then operating on it. I would expect <code>i++</code> to look something like</p> <pre><code>mov eax, [ebp+var_4] inc eax </code></pre> <p>But the actual instructions involved an extra move</p> <pre><code>mov eax, [ebp+var_4] mov ecx, eax // &lt;----- ? inc eax </code></pre> <p>In the add instruction, the extra move isn't there. When I modified the code with a decrement operation, I see that extra move as well.</p> <p>Is there some purpose for this move from <code>eax</code> to <code>ecx</code> ?</p> <p>UPDATE:</p> <p>I am still reading about registers, and from what I've read <code>ecx</code> is used as a counter, but from this code it isn't obvious what it's being used for, if anything.</p>
Why is the ecx register used during an inc instruction
|assembly|x86|
<p>There's also <a href="https://github.com/frranck/asm2c" rel="nofollow noreferrer">asm2c</a> that works on assembly source code instead of executables or objects files.</p> <blockquote> <p>Swift tool to transform DOS/PMODEW 386 TASM Assembly code to C code</p> </blockquote>
4642
2014-06-19T21:16:22.823
<p>Just started out with x86 assembly and slowly getting the hang of it. IDA produces nice graphs that make it much easier to follow all the jumps and function calls and stuff.</p> <p>I've looked at examples of arithmetics, control flow, loops, and function calls, and feel that I could reasonably take a chunk of instructions and reproduce the same logic in Java or C.</p> <p>Are there tools that will automatically take assembly and convert it to, say, C? I imagine for some people that at some point it becomes more of a chore than an exercise after doing it for years.</p>
Automatically convert x86 assembly to C
|disassembly|x86|
<p>As the first answer states, XOR is a bitewise XOR, not an XOR swap. </p> <p>To do the Xor swap that you referenced from wikipedia it takes <em>3 instructions</em> : </p> <pre><code>xor eax, ebx xor ebx, eax xor eax, ebx </code></pre> <p>Since you asked about the <em>purpose</em> of XOR I thought I would include some other concepts for you to read up on, so you might have an idea of what to expect from XORs</p> <p>You can use XOR to clear a register: </p> <pre><code>xor eax,eax </code></pre> <p>Calculate absolute value: </p> <pre><code>cdq xor eax,edx sub eax,edx </code></pre> <p>XORs can be used for Crypto: <a href="http://en.wikipedia.org/wiki/XOR_swap_algorithm">http://en.wikipedia.org/wiki/XOR_swap_algorithm</a></p> <p>XORs are used in the CRC checksum algorithm: <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">http://en.wikipedia.org/wiki/Cyclic_redundancy_check</a></p> <p>XORs can be used to calculate Gray codes: <a href="http://www.morkalork.com/mork/article/74/How_to_understand_and_use_Gray_code.htm#.U6RhN_ldXvI">http://www.morkalork.com/mork/article/74/How_to_understand_and_use_Gray_code.htm#.U6RhN_ldXvI</a></p> <p>This is just the tip of the iceberg. The instruction can be used in a large number of situations. </p>
4649
2014-06-20T14:44:03.667
<p>I have the following line in an assembler code:</p> <pre><code> XOR EAX, EBX </code></pre> <p>So, then I've searched a little bit and found out that XOR represents a "swap algorithm". You can read it here: <a href="http://en.wikipedia.org/wiki/XOR_swap_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/XOR_swap_algorithm</a></p> <p>But when I look in register window of ollydbg, then I have the following </p> <pre><code> EAX = 00000068 EBX = 0000003B </code></pre> <p>Now, after the line the register window says</p> <pre><code>EAX = 000000053 EBX = 0000003B </code></pre> <p>But from that what I have read in wikipedia article I would expect the following</p> <pre><code>EAX = 0000003B EBX = 00000053 </code></pre> <p>At the end, i can say that a normal XOR operation is performed because:</p> <pre><code>0111011 =&gt;EAX=0000003B 1101000 =&gt;EBX=00000068 ------- 1010011 =&gt;EAX=00000053 </code></pre> <p>So my question would be why the swap algorithm is not performed. Or in other words: When can I expect the swap algorithm?</p>
Has XOR EAX, EBX another purpose?
|assembly|
<p>Oleh Yuschuk released a light-weight open-source assembler library that you can download from <a href="http://ollydbg.de/srcdescr.htm" rel="nofollow noreferrer">http://ollydbg.de/srcdescr.htm</a></p> <blockquote> <p><strong>Assemble</strong></p> <p>Function Assemble(), as expected, converts command from ASCII form to binary 32 bit code.</p> </blockquote> <p>Example:</p> <pre><code> // Assemble one of the commands above. First try form with 32-bit immediate. pasm=&quot;ADD [DWORD 475AE0],1&quot;; printf(&quot;%s:\n&quot;,pasm); j=Assemble(pasm,0x400000,&amp;am,0,0,errtext); n=sprintf(s,&quot;%3i &quot;,j); for (i=0; i&lt;j; i++) n+=sprintf(s+n,&quot;%02X &quot;,am.code[i]); if (j&lt;=0) sprintf(s+n,&quot; error=\&quot;%s\&quot;&quot;,errtext); printf(&quot;%s\n&quot;,s); </code></pre>
4664
2014-06-21T13:11:37.690
<p>I'm writing a handy reverse tool in C++ with manual assembling/disassembling shell, to automate my work!</p> <p>I need an assembler library. Is there any library, embedding in C++?</p>
Automated Assembly/Disassemble library
|binary-analysis|dynamic-analysis|
<p>The toolbox <a href="http://www.muppetlabs.com/%7Ebreadbox/software/elfkickers.html" rel="nofollow noreferrer">ELFKicker</a> has an utility called <code>sstrip</code> that strip an ELF executable down to the bones.</p> <p>But, it seems that you are using Mach-O executable format. So, I would recommend to look at the <a href="https://github.com/BR903/ELFkickers/blob/master/sstrip/sstrip.c" rel="nofollow noreferrer">source code of <code>sstrip</code></a> and build your own stripper.</p> <p>You can also take a look at the <a href="https://github.com/gdbinit/otool-ng/blob/master/cctools/misc/strip.c" rel="nofollow noreferrer">source code of the <code>strip</code> command for Mach-O</a> and get inspiration. And, also, this <a href="https://web.archive.org/web/20150528181706/http://src.chromium.org/svn/trunk/src/build/mac/strip_save_dsym" rel="nofollow noreferrer">Python script <code>strip_save_dsym</code></a> might also give some hints.</p> <p>Finally, here are a few comparisons between ELF and Mach-O formats:</p> <ul> <li><a href="http://timetobleed.com/dynamic-linking-elf-vs-mach-o/" rel="nofollow noreferrer">Dynamic Linking: ELF vs. Mach-O</a></li> <li><a href="http://timetobleed.com/dynamic-symbol-table-duel-elf-vs-mach-o-round-2/" rel="nofollow noreferrer">Dynamic symbol table duel: ELF vs Mach-O, round 2</a></li> <li><a href="https://web.archive.org/web/20200103161741/http://osxbook.com/blog/2009/03/15/crafting-a-tiny-mach-o-executable/" rel="nofollow noreferrer">Crafting a Tiny Mach-O Executable</a></li> </ul>
4668
2014-06-22T22:47:57.087
<p>I've noticed that, even after stripping symbols from my executable, class names and their methods are still included at the end of the executable file.</p> <p>For instance:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Clingons { public: void clingForever() { cout &lt;&lt; "Qapla" &lt;&lt; endl; } }; int main(int argc, char *argv[]) { Clingons cling; cling.clingForever(); return 0; } </code></pre> <p>Then compile and link with:</p> <pre><code>g++ cling.cpp -o cling </code></pre> <p>Now, when I look at the bottom of the resulting "cling" file with a hex editor, I can see the "Clingons" class name along with it's methods. I can also see this information while debugging..</p> <p>even after I strip them:</p> <pre><code>strip -x cling </code></pre> <p>I can still see the same information.</p> <p>So why wasn't this information stripped away when I used the command above? Is there a way to strip (or mangle) this information other than by hand?</p> <p>The used version of GCC is <code>i686-apple-darwin10-llvm-g++-4.2 (GCC) 4.2.1</code></p> <p>This is just an example case. My real project involves the Qt framework.</p>
How to strip more than symbols?
|executable|functions|symbols|
<p>I wrote something for Cortex M3 MCUs here: <a href="http://www.reddit.com/r/ReverseEngineering/comments/21kgtc/beginners_project_logitech_g940_firmware/cgeokv3" rel="noreferrer">http://www.reddit.com/r/ReverseEngineering/comments/21kgtc/beginners_project_logitech_g940_firmware/cgeokv3</a></p> <p>As you didn't write anything about the device your blob is for and how it gets there no conclusion can be made from us.</p> <p>But you really need to know which CPU you have, where the flash memory is at and how vector tables and such work on this specific model to determine something.</p> <p>Some MCUs have a bootloader at the beginning of the flash and the user code is begind it, other MCUs have the bootloader in the upper region of the flash and user code starts at the front.</p>
4671
2014-06-23T03:13:59.103
<p>As a beginner I'm trying to load an unknown format binary file with IDA Pro,but I don't know the Image Base of this file. Are there any methods to get the Image Base. Could you also reference related papers in your answer. </p>
Image base of unknown file format?
|ida|firmware|
<p>It is just a coincidence. It happens sometimes that the value in a register be the address of some valid api which the application has nothing to do about. For reference see these images.</p> <p>I have loaded OllyDbg2 in OllyDbg2. OllyDbg2 does not import <code>kernel32.dll::BaseThreadInitThunk</code></p> <p><img src="https://i.stack.imgur.com/K1APm.jpg" alt="In Windows 7"> <strong>Ollydbg in Windows 7</strong></p> <p><img src="https://i.stack.imgur.com/Tb2Pj.jpg" alt="In Windows XP"> <strong>Ollydbg in Windows XP</strong></p> <p>In Windows 7 on entrypoint the value of <code>eax</code> is the address of <code>BaseThreadInitThunk</code>. However on Windows XP the value of <code>eax</code> is 0.</p>
4682
2014-06-24T01:49:07.347
<p>On starting <code>notepad.exe</code> with Ollydbg, I see that <code>eax</code> has a value that points at <code>kernel32.BaseThreadInitThunk</code>.</p> <p><code>notepad.exe</code> does not seem to import <code>kernel32.dll::BaseThreadInitThunk</code>. I cannot find that function, by running dependency walker on <code>notepad.exe</code>.</p> <p>How can <code>kernel32.dll::BaseThreadInitThunk</code> function be executed without importing it ?</p>
kernel32.BaseThreadInitThunk without IAT
|windows|dll|iat|
<p>Updated version of @Willem Hengeveld answer for IDA 7.4 API:</p> <pre><code>address=0x14001D020 struct_id = idaapi.opinfo_t() flags = ida_bytes.get_flags(address) if ida_bytes.get_opinfo(struct_id, address, 0, flags): struct_name = ida_struct.get_struc_name(struct_id.tid) print (f&quot;tid=0x{struct_id.tid:08x} - {struct_name}&quot;) </code></pre>
4684
2014-06-24T14:06:27.840
<p>Spotted an interesting problem when trying to determine which type of structure (since <code>isStruct(getFlags(ea))</code> returns <code>True</code>) is defined at the given address in the DB. Reading through <code>idc.py</code> didn't help much.</p> <ul> <li>Define a <code>struct</code> in the "structures" window.</li> <li>It gets assigned a <code>struct</code> ID, so, it can be accessed from IDC/Python scripts.</li> <li>Now, define a <code>struct</code> variable somewhere in e.g. the <code>.data</code> section.</li> </ul> <p>A solid example:</p> <pre><code># Some Python code strid = idaapi.get_struc_id('_s__RTTIClassHierarchyDescriptor') size = idaapi.get_struc_size(strid) idaapi.doStruct(ea, size, strid) </code></pre> <p>How, knowing the <code>ea</code>, do I get the <code>strid</code> value ?</p>
IDAPython: Get struct id defined at an address
|idapython|
<pre><code>form = idaapi.find_widget(&quot;Output window&quot;) idaapi.activate_widget(form, True) idaapi.process_ui_action(&quot;msglist:Clear&quot;) print('---------------IDA Python Running at {}---------------------'.format(datetime.datetime.now())) </code></pre>
4693
2014-06-25T01:38:02.203
<p>As a beginner I'm trying to use IDC to clear output window in IDA Pro,but I don't know which function will work.</p> <p>My IDA Pro version is 6.1.</p>
How to use IDC to clear output window in IDA Pro?
|ida|
<p>It's not very reliable. IDA can't determine types beyond analyzing the size and type of loads and stores. For instance IDA doesn't tell the difference between a pointer to a type and an integer, given that they're the same size, as far as I know. Other than that all it can do is propagate type information entered by the user. I believe the Hex-Rays decompiler does a bit more advanced argument analysis but it's also not able to extract correct function signatures in many cases.</p> <p>Argument counts can be guessed from stack pushes and stack accesses on x86 but it's important to remember that there's no requirement that the calling convention use the stack at all. On less register starved architectures, determining argument counts is bit harder due to more efficient calling conventions using registers instead of the stack.</p> <p>If you want to actually call that function it's extremely likely that you'll want to analyze it in more detail than what IDA gives you automatically.</p>
4694
2014-06-25T04:38:42.633
<p>I am using IDA to find out parameters of a routine in a DLL. I browsed to the routine in question and saw that IDA has automatically done that job for me and put a comment like this:</p> <pre><code> ; =============== S U B R O U T I N E ======================================= CODE:0048E5BC CODE:0048E5BC ; Attributes: bp-based frame CODE:0048E5BC CODE:0048E5BC ; int __stdcall Active(int, double, double, double, char, char, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, char) </code></pre> <p>I want to know how much reliable this info is if I want to call this function in C# (using p/invoke)?</p>
IDApro subroutine analysis
|ida|dll|functions|c#|
<p>If you can patch the program's image, you don't actually need to hardcode the address. you can simply add another import entry to the already existing import tables and have it patched in automatically by the loader.</p> <p>See <a href="http://www.programminghorizon.com/win32assembly/pe-tut6.html" rel="nofollow" title="Iczelion's import table tutorial">Iczelion's tutorial</a> on import tables to guide you further.</p> <p>Of course, if you're trying to do that from shellcode, you'll need to walk the loader data, locating the DLL image. The <code>Ldr</code> member in <a href="http://en.wikipedia.org/wiki/Process_Environment_Block%20%22PEB%20structure" rel="nofollow">PEB</a> should help you with that.</p> <p>If you'd be so kind to provide more details on what exactly you are trying to do, I'll update the answer; there is no simple answer to the "how to defeat ASLR" question.</p>
4703
2014-06-26T05:55:09.483
<p>The conditions: say one patched programm has hardcoded address of <code>printf()</code> from dynamically loaded <code>msvcrt80.dll</code>. It works just fine on XP, but Win7 randomizes address space (ASLR), so this trick become impossible and program crashes with call of my hardcoded <code>printf()</code> address.</p> <p>What should I do to retrieve IAT RVA of this <code>printf()</code> in win7 to make this work?</p>
Win7 ASLR bypass
|windows|exploit|
<p>Since you say you are trying to reverse an executable which stores some python bytecode in a variable, it means probably the executable <a href="https://docs.python.org/2/extending/embedding.html" rel="nofollow"><em>embeds python</em></a>. If the code is likely to be executed at some point of time, you can use a debugger.</p> <p>Set a breakpoint on <strong><a href="https://docs.python.org/2/c-api/veryhigh.html?highlight=pyeval_evalframeex#PyEval_EvalFrameEx" rel="nofollow">PyEval_EvalFrameEx</a></strong> . </p> <p>It has a prototype of <code>PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)</code></p> <p>The first parameter <code>PyFrameObject</code> has the following structure.</p> <pre><code>typedef struct _frame { PyObject_VAR_HEAD struct _frame *f_back; /* previous frame, or NULL */ PyCodeObject *f_code; /* code segment */ PyObject *f_builtins; /* builtin symbol table (PyDictObject) */ PyObject *f_globals; /* global symbol table (PyDictObject) */ PyObject *f_locals; /* local symbol table (any mapping) */ PyObject **f_valuestack; /* points after the last local */ PyObject **f_stacktop; PyObject *f_trace; /* Trace function */ PyObject *f_exc_type, *f_exc_value, *f_exc_traceback; PyThreadState *f_tstate; int f_lasti; /* Last instruction if called */ int f_lineno; /* Current line number */ int f_iblock; /* index in f_blockstack */ PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */ PyObject *f_localsplus[1]; /* locals+stack, dynamically sized */ } PyFrameObject; </code></pre> <p>The <em>third</em> member of <code>PyFrameObject</code> is <code>PyCodeObject</code>.</p> <p><code>PyCodeObject</code> has the following structure.</p> <pre><code>typedef struct { PyObject_HEAD int co_argcount; /* #arguments, except *args */ int co_nlocals; /* #local variables */ int co_stacksize; /* #entries needed for evaluation stack */ int co_flags; /* CO_..., see below */ PyObject *co_code; /* instruction opcodes */ PyObject *co_consts; /* list (constants used) */ PyObject *co_names; /* list of strings (names used) */ PyObject *co_varnames; /* tuple of strings (local variable names) */ PyObject *co_freevars; /* tuple of strings (free variable names) */ PyObject *co_cellvars; /* tuple of strings (cell variable names) */ /* The rest doesn't count for hash/cmp */ PyObject *co_filename; /* string (where it was loaded from) */ PyObject *co_name; /* string (name, for reference) */ int co_firstlineno; /* first source line number */ PyObject *co_lnotab; /* string (encoding addr&lt;-&gt;lineno mapping) */ void *co_zombieframe; /* for optimization only (see frameobject.c) */ } PyCodeObject; </code></pre> <p>The <em>sixth</em> member of the above structure is <code>co_code</code> . It is basically a <code>PyStringObject</code>. It has the following structure.</p> <pre><code>typedef struct { PyObject_VAR_HEAD long ob_shash; int ob_sstate; char ob_sval[1]; } PyStringObject; </code></pre> <p>The <code>ob_sval</code> contains the bytecode you are after. So once you hit <code>PyEval_EvalFrameEx</code> follow the structures in memory to get the bytecode.</p> <p>Another thing to note is you need to know the layout of <code>PyObject_VAR_HEAD</code> and <code>PyObject_HEAD</code> to get the actual offsets. Refer to the <a href="http://hg.python.org/cpython/file/3124790c07b4" rel="nofollow">python source</a> for more information.</p>
4716
2014-06-27T04:00:34.400
<p>I'm trying to extact a global variable from an executable. Basically, I'm tryin to reverse an executable that put some python bytecode in a global variable and I'd like to extract it. I found out that the data is in the .data of the PE File, but I can't find a way to get it in all the data segments. Any ideas?</p>
Extract a global variable
|python|executable|
<p>Ollydbg already shows the parameters passed to a functions in the CPU window. This of course works for standard functions such as <code>printf</code> , <code>CreateFileA</code> which Ollydbg knows about. For example see the image below. The parameters to <code>CreateWindowExA</code> are shown.</p> <p><img src="https://i.stack.imgur.com/XeAoA.png" alt="enter image description here"></p> <p>Now the return value of a function is <em>usually</em> kept in register <code>eax</code> in <code>x86</code>. So just note the value after the function returns. Of course in case of a hand-coded assembly the return value may be anywhere.</p>
4720
2014-06-27T07:36:50.223
<p>The calling convention used in assembly differs depending to the compiler, so I need to know How ollydbg2.01 would help me to recognize the parameters passed from caller to the callee and the values returned back from the callee to the caller for a CALL instruction. The assembly which I am working on is compiled by Microsoft visual C++.</p>
Would OllyDbg help recognizing the passed parameters between the caller and the calle?
|ollydbg|
<p>If the surrounding window seems to be a genuine window, but the individual buttons are not, I'd assume that</p> <ul> <li>The surrounding window displays a bitmap, or does whatever else is needed to display the individual buttons</li> <li>The surrounding window reacts on mouse clicks</li> <li>And, the surrounding window determines itself which "button" is used by looking at the mouse coordinates at the time of the mouse click.</li> </ul> <p>So, what we want to do is, start the program in a debugger, and use a breakpoint that is triggered when the mouse click occurs. The problem is, the window procedure gets called a lot of times, with all kind of messages, while you want to break on some of them (for example, <code>WM_LBUTTONDOWN</code>), but not on most of the others (for example, <code>WM_PAINT</code>).</p> <ul> <li>Ollydbg can do this directly - place a conditional breakpoint that triggers depending on the window message.</li> <li>If, for whatever reason, you can't use that feature, you need to disassemble (and partially understand) the window procedure. It will receive 4 parameters on the stack, the 2nd of which is the window message (see <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633570%28v=vs.85%29.aspx" rel="nofollow">Using Window Procedures</a>). The window procedure will, at some point, compare this parameter to the values of well-known window message IDs. You might be interested in <code>WM_LBUTTONDOWN</code> (<code>0x0201</code>) or one of the other <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645533%28v=vs.85%29.aspx" rel="nofollow">Mouse Input Events</a>). Check where the code branches to when it receives one of those "interesting" messages, and place a breakpoint on that branch.</li> </ul> <p>After placing a suitable breakpoint, run your application in the debugger, click the mouse, and hope the debugger actually hits the breakpoint. If it doesn't, check which mistake you've made.</p> <p>Single-Step your code. It will probably fetch parameter 4 from the stack, which encodes the X and Y coordinates of the mouse, and compare these parameters to something - chances are, there's an array of structures that defines rectangles and jump addresses, and a loop that checks against each entry.</p> <p>Once you've found that, you're finished.</p> <p>Sounds too easy? It probably is, because, depending on your framework, the actual comparisons might be buried deeply in stuff that was a bunch of C++ classes in the original source, and there might be various calls, some of them indirect (in the case of C++ class methods) until you get to the "interesting" position.</p> <ul> <li><p>Sometimes it's easier to use Ollydbg to resolve this. Single-Step the source after your breakpoint, using "step over" to step over function calls. Whenever you see something interested happened within the function call, note the address. Restart your program, run to your breakpoint, run to the address you noted, and "step into" the function this time. This will allow you to put the finger on the interesting code relatively quickly, while stepping over all the <code>strcmp()</code> and <code>malloc()</code> and <code>WriteALotOfStuffToSomeFileIfDebuggingIsOn()</code> functions.</p></li> <li><p>Sometimes it's easier to use IDA. Generate a call tree from your window procedure, focus on the first 3-5 levels. Search your code for occurrences of magic numbers, like the <code>0x0201</code> above. Check if one of these is a <code>CMP XX, 0x0201</code> in one of the functions in your call tree. This might be just the position you're looking for.</p></li> <li><p>Make a screen shot, and paste it into some image viewer program (I like <code>Irfanview</code> for that). Get the pixel coordinates of the button within the frame window. Search, in the data section, for those values, surrounded by what looks like a table of similar data. This might be your coordinate/jump table. If you find something, place a hardware breakpoint on it to find out when that memory gets accessed, or use the IDA cross reference list to get respective addresses in your code.</p></li> </ul>
4724
2014-06-27T13:42:34.377
<p>I just started using IDA and OllyDbg, although I am experienced developer but before this I was reverse engineering only Java and .Net code which is much more easy task comparing of what I need to do now.</p> <p>I have an application which has some buttons that are not accessible by Spy++ and WinInspector and all other tools that I tried. Spy++ sees only the <code>selectorclass</code> which is the whole panel where buttons are placed. I've managed to find where the <code>WndProc</code> of this selector is and even the method wich takes hwnd of <code>SelectorControl</code> from <code>GetPropA</code> method, but I have trouble identifying the click itself, so i don't know where the actual button is clicked and where there the app knows what exact button is clicked and what handler to use. </p> <p>I would like to ask for some tips which are maybe useful to know but are not known by newbies like me. What are strategies that can be used here?</p> <p>Maybe there are some ways to identify what framework was used, so I can play with that framework to know what to look for.</p>
Custom UI buttons
|ida|ollydbg|c++|
<ul> <li><a href="http://www.asmirvine.com/" rel="nofollow">Assembly Language for x86 Processors</a> by Kip Irvine</li> <li><a href="http://www.agner.org/optimize/" rel="nofollow">Optimization manuals</a> by Agner</li> <li><a href="http://www.microsoft.com/msj/0298/hood0298.aspx" rel="nofollow">Under the Hood article</a> by Matt Pietrek </li> <li><a href="https://wiki.skullsecurity.org/Assembly_Summary" rel="nofollow">Skull Security Assembly Summary</a></li> <li><a href="http://www.duntemann.com/assembly.html" rel="nofollow">Assembly Language Step By Step for Linux</a> by Jeff Duntemann</li> <li><a href="https://software.intel.com/en-us/articles/introduction-to-x64-assembly" rel="nofollow">Introduction to x64 Assembly</a></li> <li><a href="http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html?iid=tech_vt_tech%2064-32_manuals" rel="nofollow">Intel Manuals</a> </li> <li><a href="http://www.tutorialspoint.com/assembly_programming/" rel="nofollow">Tutorials Point</a></li> </ul>
4734
2014-06-28T22:52:22.873
<p>I am trying to understand assembly and buffer overflows on a 64bit Intel i7 machine. I am having a lot of questions. <a href="https://stackoverflow.com/questions/24462106/what-do-the-cfi-directives-mean-and-some-more-questions">I asked on SO</a> but I don't have any satisfactory answers. I also don't get why there are <code>MOV</code> instructions to EEDI, ESI and EDI instead of <code>PUSH</code> instructions. Perhaps I should understand assembly on modern architectures first. Can anyone answer my qustions and point me to right learning resources for modern architectures? (I am asking here because people doing REing do have knowledge about assembly and are more targeted audience as compared to the broader audience on SO)</p>
Any guides on modern assembly?
|assembly|
<p>Past TEMU user here. Perhaps you should attempt to understand TEMU more (which I don't), to prevent duplicating the work already done. PTRACE only records syscall transitions, but if you go under QEMU, a better granularity is basic blocks. Not sure if TEMU has the capacity to do that, the idea is the each basic block can uniquely identify part of the path taken, without going into lower level of details at the registers/values level. ie, less noise, but more refined than syscall. Knowing the the full state of the registers at each entry and exit point of the basic block, can almost deterministically decide what is the path the entire execution trace will look like, minus all the intermediate registers values, which can be derived if need to. ("almost", because asynchronous event like interrupt can happened).</p> <p>Update:</p> <p>There is another option: <a href="http://wiki.qemu.org/" rel="nofollow">QEmu</a> + <a href="http://www.lttng.org/" rel="nofollow">Lttng</a>, but since default Qemu does not provide that feature, you have to download the QEMU source code, and compile it to enable lttn-ust tracing.</p> <p><a href="http://linuxmogeb.blogspot.sg/2014/08/how-to-trace-qemu-using-lttng-ust.html" rel="nofollow">http://linuxmogeb.blogspot.sg/2014/08/how-to-trace-qemu-using-lttng-ust.html</a></p>
4738
2014-06-30T09:21:37.473
<p>My original point was to build something a bit more powerful and generic than a <code>PTRACE</code> system call for Linux platforms. The problem with <code>PTRACE</code> is that it only run on your own system and architecture.</p> <p>An idea would be to run a virtual machine (or, better, an emulator) with a different operating system and a (possibly) different architecture on it.</p> <p>While looking for the ideal candidates, I found the <a href="http://en.wikibooks.org/wiki/QEMU/Monitor">QEmu monitor interface</a> and several projects using <a href="http://wiki.qemu.org/Main_Page">QEmu</a> as OS/architecture emulator to collect traces:</p> <ul> <li><a href="http://www.s3.eurecom.fr/tools/avatar/">Avatar</a></li> <li><a href="https://code.google.com/p/decaf-platform/wiki/DECAF">DECAF</a> (successor of TEMU)</li> <li><a href="https://github.com/moyix/panda">PANDA</a></li> <li><a href="http://s2e.epfl.ch/">S2E</a> (seems to be a sub-component of Avatar?)</li> <li><a href="http://bitblaze.cs.berkeley.edu/temu.html">TEMU</a> (<a href="http://bitblaze.cs.berkeley.edu/">Bitblaze</a>)</li> </ul> <p>The features I want are similar to the <code>PTRACE</code> interface (freeze execution, step by step runs, memory and registers read and write, ...) all with several OSes and several architectures. </p> <p>My questions:</p> <ul> <li>Did I forgot some similar projects in my list ?</li> <li>Can the QEmu monitor interface provide a system/architecture agnostic <code>PTRACE</code> interface just as I want ? And, if not, what are the main issues I might run into while implementing it inside QEmu ?</li> </ul>
Using QEmu monitor interface to extract execution traces from a binary?
|dynamic-analysis|qemu|
<p>In Australia, you need to have a valid license for the software and be reversing for "compatibility" purposes. Which is pretty wide and includes investigating a security issue. Obviously if the code is available from the vendor, you need to get hold of that source code instead of reversing.</p>
4744
2014-07-01T03:07:00.030
<p>How "legal" is it to read and edit .exe files, .dll files, and other compiled source files? Decompilation is taking the compiled code of a program, often minified and obfuscated, and trying to get the original source code back as it was written, or at least get it in a form a person could read. There are various reasons a person or company would make its code harder to read while compiling it, but the 2 I've seen most often have to do with saving resources, like space, RAM, power, etc., and making it so the code is harder to read so the user can not see what it does as easily. As we are a community about questioning the practices of reverse engineering, I think it's safe to say most of us don't like the second reason. I am asking for facts here, though, not opinions.</p> <p>Because this question could get very broad, I will limit this to laws in particular countries and rules of various influential or popular companies, but info about generalities is also welcome. I am definitely not asking about morals/ethics, although I know those will certainly come up.</p> <p>There was already <a href="https://reverseengineering.stackexchange.com/questions/60/is-reverse-engineering-and-using-parts-of-a-closed-source-application-legal">a question about the legality of reverse engineering in general</a>, but I'm talking only about decompilation here. As the answers to this question stated, decompilation is one type of reverse engineering. As far as I could tell, the other question didn't get answers about decompilation specifically, though you are free to provide these yourself. One answer did say the question was too broad, but perhaps this question will have a better scope.</p>
Legality of Decompilation
|decompilation|law|
<p>The first thing that comes to my mind is for you to create a class with a few virtual methods, which will be used as the test subject. Then from your ActiveX control you'd expose methods that manipulate the variable, say:</p> <ul> <li>Method #1: Allocate the test object and keep the pointer in a static variable</li> <li>Method #2: Call the virtual methods provided by the test object</li> <li>Method #3: Free the test object instance, <strong>without setting the pointer to NULL</strong></li> <li>Some means to allocate other things that would reuse the memory freed in the previous method</li> </ul> <p>Then whip up a basic script exercising the given methods: allocate, call the methods to make sure it works as designed, free the instance, allocate something else, call virtual methods again and crash the IE instance. ;-) Should do the trick.</p>
4748
2014-07-01T08:39:53.470
<p><strong>Use After Free</strong> bugs a getting more severe these days.</p> <p>I'm planning to demonstrate Use After Free bug exploitation using <strong>VTable overwrite</strong>. So, I'm trying to create a <strong>ATL ActiveX Control</strong> which is vulnerable to Use After Free bug using <strong>Internet Explorer 9 or 10</strong>.</p> <p>I'm having trouble to come up with a <strong>Use After Free vulnerable code</strong> that works. Does anyone has experience with this kind of bug and can anyone try to help me.</p> <p>I'm trying too. If I'm able to get it working, I'll share it here:</p> <pre><code>class User { public: virtual void SetUsername() { } }; class NewUser:public User { char username[20]; public: virtual void SetUserName(char* strUsername) { strcpy(username, strUsername); } virtual char* GetUserName() { return username; } }; STDMETHODIMP CATLActivexControl::CreateUser(BSTR sUserName, DOUBLE* retVal) { USES_CONVERSION; char *tmp = W2A(sUserName); NewUser *nuser = new NewUser; nuser-&gt;SetUserName(tmp); free(nuser); char *xyz = nuser-&gt;GetUserNameW(); return S_OK; } </code></pre> <p><strong>I worked on the above example and I have come up with a nicer solution which really triggers Use After Free.</strong></p> <p><strong>C++ code</strong></p> <pre><code>#include "stdafx.h" #include "ATLStudentActiveXControl.h" // Virtual Function defination class User { public: virtual void Add(char* uName) = 0; virtual char* GetName() = 0; }; class Student : public User { private: char s_name[30]; public: virtual void Add(char* uName) { strncpy(s_name, uName, sizeof(s_name)); } virtual char* GetName() { return s_name; } }; Student *pStudent = new Student; STDMETHODIMP CATLStudentActiveXControl::Add(BSTR sName) { USES_CONVERSION; char *tStudent = W2A(sName); pStudent-&gt;Add(tStudent); return S_OK; } STDMETHODIMP CATLStudentActiveXControl::Delete() { free(pStudent); return S_OK; } STDMETHODIMP CATLStudentActiveXControl::GetName(BSTR* sName) { char *tStudent = pStudent-&gt;GetName(); *sName = A2WBSTR(tStudent); return S_OK; } </code></pre> <p><strong>HTML Code</strong></p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Use After Free - Test Page&lt;/TITLE&gt; &lt;script language="javascript" type="text/javascript"&gt; function UAF() { alert('Start'); // Assign _studentActiveX variable to ATLStudentActiveXControl var _studentActiveX = document.getElementById("ATLStudentActiveXControl"); // Add a student _studentActiveX.Add("StudentName"); // Uncomment the below line to trigger Use After Free vulnerability // _studentActiveX.Delete(); // Get the name of the added student var _studentName = _studentActiveX.GetName(); alert(_studentName); // Delete the student _studentActiveX.Delete() alert('Done'); } &lt;/script&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;OBJECT ID="ATLStudentActiveXControl" CLASSID="CLSID:9EACDFCF-1A2E-462E-9DF6-53E03936DB22"&gt;&lt;/OBJECT&gt; &lt;div&gt; &lt;p&gt;Demonstrating &lt;b&gt;Use After Free&lt;/b&gt; vulnerability.&lt;/p&gt; &lt;input type="button" onclick="UAF();" value="Use After Free" /&gt; &lt;/div&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>Please share your views. Thanks.</p>
Use After Free - Example
|debugging|exploit|vulnerability-analysis|
<p>The <kbd>Y</kbd> key equivalent is indeed the <code>SetType</code> (or, rather, <code>ApplyType</code>) function, and it normally accepts addresses. However, you actually can pass the structure member ID as the "address" to set the member's type info.</p>
4750
2014-07-01T16:52:52.690
<p>The ordinary, manual way of redefining a <code>struct</code> member to become a function pointer would be to press on it, hit '<kbd>Y</kbd>', and enter the proper declaration in the popup box. For example, for <code>struct</code> member <code>fncQuery</code>, I would change the string to: <code>BOOL (__cdecl *fncQuery)(char *cmdID)</code></p> <p>This would be helpful; When I next identify a call to this function pointer, I would mark the appropriate <code>call [reg+offset]</code> line as this function pointer, and IDA will re-analyze and comment the parameters for me.</p> <p>I have a thousand <code>struct</code> each with at least one such function pointer member, and corresponding lists of the descriptions of these functions' parameters and return values. Understandably, I want to match them up by an IDAPython script rather than by hand. However, I can't find an equivalent for the '<kbd>Y</kbd>' button for scripts:</p> <ul> <li><p><code>AddStrucMember</code> does not cut it as far as I know - I can declare a member to become a pointer to a <code>struct</code> by giving it a <code>structID</code>, but that's not what I need.</p></li> <li><p><code>SetMemberType</code> is the same as the previous.</p></li> <li><p><code>SetType</code> requires a linear address and a type string - which would be perfect except linear addresses are exclusive to the code section, so I can't touch structure member definitions with <code>SetType</code>.</p></li> </ul> <p>In my search I've found someone who conjured up dark magic, incorporating low level <code>idaapi</code> into his IDAPython script, to detect if a <code>struct</code> member has the same name as a known function, and if it does, "<em>gets</em>" the type of that function and "<em>sets</em>" it onto the member. Specifically, such horrible calls are seen (taken out of context of its definitions, you'll have to trust me when I say this runs properly and the first function call fills up its many outparameters with meaningful values):</p> <pre><code>get_named_type = g_dll.get_named_type get_named_type.argtypes = [ ctypes.c_void_p, #const til_t *ti, ctypes.c_char_p, #const char *name, ctypes.c_int, #int ntf_flags, ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const type_t **type=NULL, ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const p_list **fields=NULL, ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const char **cmt=NULL, ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const p_list **fieldcmts=NULL, ctypes.POINTER(ctypes.c_ulong), #sclass_t *sclass=NULL, ctypes.POINTER(ctypes.c_ulong), #uint32 *value=NULL); ] get_named_type( til, funcname, idaapi.NTF_SYMM, ctypes.byref(typ_type), ctypes.byref(typ_fields), ctypes.byref(typ_cmt), ctypes.byref(typ_fieldcmts), ctypes.byref(typ_sclass), ctypes.byref(value) type_arr = ctypes.create_string_buffer(0x400) type_arr[0] = chr(idaapi.BT_PTR) manualTypeCopy(type_arr, 1, len(type_arr), typ_type) ret = g_dll.set_member_tinfo( til, struc, memb, ctypes.c_uint(0), type_arr, typ_fields, ctypes.c_uint(0), ) </code></pre> <p>The work behind the scenes on "<code>get_named_type</code>" eludes me, and looking into its source (and fashioning something from it for my use) may be strong headed and premature.</p> <p>Do you know of an easier way my need can be fulfilled ? I just need to define structure members as function pointers from an IDAPython script. Please help !</p>
Setting an IDA function pointer in a struct via script
|ida|idapython|struct|
<p>If you're using GAS or a compatible assembler, you can use special modifiers to have it emit relocation info for GOT-based addressing.</p> <p>Here's the <code>gcc -S</code> output of a typical prolog of a function compiled with <code>-fPIC</code>:</p> <pre><code>call __i686.get_pc_thunk.bx addl $_GLOBAL_OFFSET_TABLE_, %ebx leal .LC0@GOTOFF(%ebx), %eax movl %eax, (%esp) call puts@PLT </code></pre> <p>As you can see, you can replace the <code>%ebx</code> addendum with <code>$_GLOBAL_OFFSET_TABLE_</code>, and other GOT-relative offsets with <code>symbol@GOTOFF</code>. In some cases you may also need <code>@GOTPLT</code> or <code>@GOTPCREL</code> modifiers. See <a href="http://www.mindfruit.co.uk/2012/06/relocations-relocations.html" rel="nofollow">here</a> for more info (mostly x64-specific, but still useful).</p> <p>If your file is relocatable or a shared object, disassembling it with <code>-dr</code> (so you see relocation info) can be useful to see places where you may need to add back the symbol modifiers.</p>
4751
2014-07-01T18:57:58.567
<p>Basically I am trying to re-use some asm code disassembled from a binary on x86 32bit Linux.</p> <p>I am facing some trouble when references of GOT/GOT.PLT involved like these.</p> <pre><code> .... 804c460: 53 push %ebx 804c461: e8 ec ff ff ff call 804c452 &lt;__i686.get_pc_thunk.bx&gt; 804c466: 81 c3 8e 2b 00 00 add $0x2b8e,%ebx // %ebx has the beginning address of GOT table 804c46c: 83 ec 18 sub $0x18,%esp .... </code></pre> <p>If I want to re-use these asm code, I have to <strong>lift concrete address into symbols</strong>, and it seems that in the above code, I have to find a way to let <code>ebx</code> store the begin address of <code>GOT</code> table.</p> <p>Well... then do I have to modify the linker...? Because the begin address of <code>GOT</code> table can't be decided until link time..</p> <p>So my questions are:</p> <ol> <li><p>Is modifying linker a right way to do this ..? Is there any other way?</p></li> <li><p>How to modify the linker in this issue..? I basically have no experiences before.. </p></li> </ol>
How to re-use some asm code when GOT/GOT.PLT references involved?
|disassembly|assembly|reassembly|dynamic-linking|
<p>Issue solved. For that moment tested several utilities for relocation patching. </p> <p><a href="http://www.woodmann.com/collaborative/tools/index.php/RelocEditor" rel="nofollow">RelocEditor</a> - didn't solve the issue, but maybe for some future researchers who will face with similar task will find it useful </p> <p><a href="https://yadi.sk/d/58FFCzwdVkTuo" rel="nofollow">Reloc Rebuilder</a> - actually solved issue. Just select patched executable and app should fix the relocation table.</p> <p><a href="https://github.com/gta126/Relocation-Section-Editor" rel="nofollow">Relocation Section Editor</a> - didn't tried myself, but should also work. Link here because of purposes as in first item.</p>
4752
2014-07-02T05:56:23.083
<p>Now working on binary analysis of PE and stuck on tricky (for me), ungoogleable question.</p> <p>For instance, I've binary, that needs to be patched. So after doing that will be awesome, if there is way to insert address of my function to relocation table. The following picture can illustrate thing I'm talking about.</p> <p><img src="https://i.stack.imgur.com/bk5RQ.png" alt="Relocated functions in binary"></p> <p>So, as you can see, relocated functions marked pale, and my function is not in the relocation table. What should I patch to add my function into relocation table? Tried CFF Explorer with no luck. All the patches was made in hiew.</p>
Relocation table patching
|assembly|
<p>A common issue is missing <code>symsrv.dll</code>. Please make sure you have it on the remote machine and that <code>win32_remote.exe</code> can find it.</p> <p>You can also append <code>-z10000</code> to the command line in order to get more output from the MS-DIA libraries.</p> <p>Thanks to HexRays for this answer.</p>
4757
2014-07-02T11:42:49.730
<p>When I try to load a Portable Executable in IDA Pro 6.6 it can't resolve the Symbols. I have hooked it to a <code>win32_remote.exe</code>. It keeps saying <code>E_PDB_NOT_FOUND</code>. </p> <p>I even have WinDBG installed.</p>
IDA fails to load Symbols from EXE on Linux
|ida|symbols|
<p>Solved it after trying many things.</p> <p>I had to change the data area to a byte array with</p> <pre><code> MakeByte(source); MakeArray(source, byte_count); </code></pre> <p>after the <code>MakeUnknown</code>, and then call <code>SetHidden</code> with value <code>0</code></p> <p>Also to the Hiding the Area with keyboard, the new default keys are <kbd>Ctrl</kbd>+<kbd>-</kbd>, the displayed text in IDA is wrong.</p> <p>thus final code was:</p> <pre><code>static idc_memcpy(source, dest, byte_count, desc) { auto i, val; SetCharPrm(INF_GENFLAGS, INFFL_LOADIDC|GetCharPrm(INF_GENFLAGS)); Message("Copy %a: Start\n", dest); for(i = 0; i &lt; byte_count; i = i + 2 ) { val = Word(source + i); PatchWord(dest + i, val); } SetCharPrm(INF_GENFLAGS, ~INFFL_LOADIDC&amp;GetCharPrm(INF_GENFLAGS)); MakeUnknown(source,byte_count,DOUNK_EXPAND+DOUNK_DELNAMES); MakeByte(source); MakeArray(source, byte_count); HideArea(source, source+byte_count, desc, "", "", -1); SetHiddenArea(source, 0 ); Message("Copy %a: End\n", dest); } </code></pre>
4770
2014-07-02T23:13:55.980
<p>I'm using the following IDC function to copy the RAM Data and Code sections from the packed binary, into the correct runtime locations for my Fujitsu FR system:</p> <pre><code>static idc_memcpy(source, dest, count, desc) { auto i, val; SetCharPrm(INF_GENFLAGS, INFFL_LOADIDC|GetCharPrm(INF_GENFLAGS)); Message("Copy %a: Start\n", dest); for(i = 0; i &lt; count; i = i + 2 ) { val = Word(source + i); PatchWord(dest + i, val); } SetCharPrm(INF_GENFLAGS, ~INFFL_LOADIDC&amp;GetCharPrm(INF_GENFLAGS)); MakeUnknown(source,count,DOUNK_EXPAND+DOUNK_DELNAMES); HideArea(source, source+count-1, desc, "", "", -1); SetHiddenArea(source, 1 ); Message("Copy %a: End\n", dest); } </code></pre> <p>But when I go to the source address I see: </p> <pre><code>ROM:00447E8C ; [0000C878 BYTES: BEGIN OF AREA RAM Data2 Source. PRESS KEYPAD "-" TO COLLAPSE] ROM:00447E8C unk_447E8C: .byte 0xFF ; DATA XREF: Tsk32+176o ROM:00447E8D .byte 0xFF ROM:00447E8E .byte 0xFF ROM:00447E8F .byte 0xFF ROM:00447E90 .byte 0 ROM:00447E91 .byte 0x30 ; 0 ROM:00447E92 .byte 0 ROM:00447E93 .byte 0 </code></pre> <p>I was hoping/expecting to have that area hidden, what am I doing wrong. If I press keypad <kbd>-</kbd> I get the error message:</p> <blockquote> <p>IDA failed to display the program in graph mode. Only instructions belonging to functions can be displayed in graph mode.</p> </blockquote>
Hide data areas in IDA IDC
|ida|
<p>As far as the screenshot depicts, I can say that you are on the right track. You have correctly, overwritten the <strong>Pointer to NextSEH</strong> and <strong>SE Handler</strong>.</p> <h1><strong>Some explanation:</strong></h1> <p><strong>Exception Registration Record Structure</strong></p> <pre><code>typedef struct _EXCEPTION_REGISTRATION_RECORD { struct _EXCEPTION_REGISTRATION_RECORD *Next; PEXCEPTION_ROUTINE Handler; } EXCEPTION_REGISTRATION_RECORD, *PEXCEPTION_REGISTRATION_RECORD; </code></pre> <p>Whenever a new function is called which has exception handling mechanism, the <strong>EXCEPTION_REGISTRATION_RECORD</strong> is added to the stack. Where <strong>*Next</strong> is the pointer to the <strong>Previous EXCEPTION_REGISTRATION_RECORD</strong> and <strong>Handler</strong> is the function pointer to the <strong>Exception handler</strong>.</p> <p>The <strong>FS:0</strong> register always points to the first <strong>EXCEPTION_REGISTRATION_RECORD</strong>. Once the <strong>EXCEPTION_REGISTRATION_RECORD</strong> is pushed on the stack, the <strong>FS:0</strong> register will be set to point to the new <strong>EXCEPTION_REGISTRATION_RECORD</strong> and <strong>Next</strong> record will be set to point to the previous value of <strong>FS:0</strong> register. This will maintain the link list of the SEH chains.</p> <p><strong>ExceptionHandler Structure</strong></p> <pre><code>typedef EXCEPTION_DISPOSITION (*ExceptionHandler) ( IN PEXCEPTION_RECORD ExceptionRecord, IN ULONG64 EstablisherFrame, IN OUT PCONTEXT ContextRecord, IN OUT PDISPATCHER_CONTEXT DispatcherContext ); </code></pre> <p>When an exception occurs, <strong>System Exception Dispatcher</strong> routine kicks in and it's sets up it's own stack frame. The structure of the <strong>ExceptionHandler</strong> is pushed to the stack. </p> <p>In SEH overwrite scenario, an attacker is lucky because, <strong>System Exception Dispatcher</strong> routine places the <strong>EstablisherFrame</strong> value on the stack at <strong>[ESP+8]</strong> before this <strong>ExceptionHandler</strong> function is called. </p> <p><strong>EstablisherFrame</strong> is the pointer to the <strong>NextSEH</strong> record. An attacker is able to control it by overwriting <strong>NextSEH</strong> record with arbitrary memory address.</p> <p><strong>Note:</strong> <em>Attacker has not overwritten the <strong>EstablisherFrame</strong>. However, the attacker has overwritten <strong>NextSEH</strong> pointer which was there on the stack.</em></p> <p>Once, you pass the exception <strong>System Exception Dispatcher</strong> passes the control to the <strong>SE handler</strong> and the exception handling code is executed.</p> <p><strong>Exploitation Tactics:</strong></p> <ol> <li>Attacker will overwrite the <strong>NextSEH</strong> with <strong>Backward Jump</strong> and the <strong>SE Handler</strong> with the address of <strong>POP/POP/RET</strong> sequence.</li> <li>Once the exception occurs, the address of <strong>NextSEH</strong> will be placed on the stack at <strong>[ESP+8]</strong> due to exception dispatch routine prologue.</li> <li>Once the exception is passed, the exception dispatcher routine will pass the control to <strong>SE Handler</strong>.</li> <li><strong>SE Handler</strong> will execute the <strong>POP/POP/RET</strong> sequence and will <strong>POP</strong> the address of <strong>NextSEH</strong> in <strong>EIP</strong>. Hence, gaining code execution.</li> </ol> <p>Please accept my apologies if there are mistakes in the answer, and please help to improve the answer so that it's useful to the community members.</p> <p>Thanks.</p>
4773
2014-06-30T18:38:00.013
<p>I am trying to exploit this little program I found on <a href="http://opensecuritytraining.info/" rel="nofollow noreferrer">opensecuritytraining.info</a>. But, somehow, I am stuck at this point. What I did was to create a file which gets read from the program. Here is the code I am using for this:</p> <pre><code>#!/usr/bin/env python import struct mystring = b"\xCC"*1096# junk nSEH = b"\xeb\x06\x90\x90" SEH = struct.pack("&lt;L", 0x004011B6) opcode = "\xe9\xdf\xf6\xff\xff" mystring += nSEH + SEH + ("\x90"*16) + opcode fileName='C:\hellothere.bin' with open(fileName, 'wb') as fb: fb.write(bytearray(mystring)) fb.close() </code></pre> <p>So, I am stuck at this point where I am overriding the buffer with <code>\xCC</code>, But my question is, when I am placing another jump code where the <code>CC</code>'s override the saved <code>EIP</code> register. Can I jump further backwards to where my shell code takes place ? </p> <p>I mean in principle this should be possible for some tweaking or adjusting of the exploit code itself.</p> <p>Any idea ?</p> <p><img src="https://i.stack.imgur.com/SWEJR.png" alt="exercise"></p>
How should I reach my shellcode?
|windows|x86|buffer-overflow|
<p>Firstly, I would mention that instead of using a general purpose hex editor, a dedicated <code>class</code> editor would be much better. There are plenty of them. </p> <p>You tried editing the <code>class</code> file and to your surprise the changes you made were not reflected. At that point you should be pretty much sure that there <em>must</em> be some other tricks such as generating the strings dynamically, encryption, obfuscation etc.The <code>class</code> files could also be loaded from some other locations such as a <code>cache</code> which you do not expect.</p> <p>One way to get information about which classes are loaded is to use the following command line switch while starting java.</p> <pre><code>java -verbose:class -jar &lt;Your jar file&gt; </code></pre> <p>This way the <code>jvm</code> will notify you when classes are loaded and from which locations. Using this you can know if there is some sort of <em>hidden</em> <code>cache</code> from which it loads <code>class</code> files.</p> <p>After this option fails, i.e. when you are sure that there is no such hidden <code>cache</code>, you can almost be sure that there is <code>encryption</code> involved or the strings are generated dynamically. <code>Decompiling</code> would help, but of course if there is no obfuscation to hinder decompiling. If everything else fails, you may try inspecting the <code>bytecode</code> of the <code>class</code>files as a last resort.</p>
4783
2014-07-04T12:31:23.680
<p>I modified the byte-code of a third party Java desktop application's <code>.class</code> file (and repacked the <code>.jar</code>), only to see that during runtime, my change made no difference, unless my change caused a crash somehow. The most simple experiment I did was to use a hex editor and simply replace a letter in a text string in the <code>.class</code> file. Runtime (of course, after restarting the Java application), the text was still the original text.</p> <p>Here's an example of the original byte-code:</p> <pre><code>ldc "Some text." </code></pre> <p>Using a hex editor, I changed the string, and looked again in the byte-code editor:</p> <pre><code>ldc "Xome text." </code></pre> <p>The decompiled code also shows the modified string. There are no more references to the original string in the <code>.class</code> file. Despite this change, the displayed text at runtime is "<em>Some text.</em>" rather than "<em>Xome text.</em>".</p> <p>Is there anything I need to take into consideration, e.g. some sort of cache (outside the scope of the application) that must be cleared? I tried to delete the "<em>Temporary Internet Files</em>" in the Java console, to no avail.</p> <p>Thank you for any assistance you can provide! :)</p> <p><strong>Removed:</strong> The decompiled code and modified files for the real-world application I was experimenting on, due to their questionable nature (didn't really help anyone anyway).</p>
Modified Java byte-code, no difference runtime
|java|byte-code|
<p>The COM Descriptor Data Directory (DD 14) is used to lookup the COR20 structure. This is how you can tell the difference between a managed executable and a native executable.</p> <p>See <a href="https://reverseengineering.stackexchange.com/questions/1614/determining-if-a-file-is-managed-code-or-not/">this question</a> for more information. Also see this introduction to the <a href="http://www.ntcore.com/files/dotnetformat.htm" rel="nofollow noreferrer">dotnet file format</a> for an overview.</p>
4789
2014-07-05T12:08:17.227
<p>Executable files created through managed framework like .Net have <code>.exe</code> extension whereas application created through languages like C++ also has <code>.exe</code> extension. How does the OS knows whether to run the application through managed framework like .Net or directly ?</p>
How does the OS distinguish between executable types
|windows|executable|
<p>PE files have several sections like <code>.code</code> , <code>.data</code>, <code>.bss</code> etc. Each of the sections have a special purpose, such as the <code>.code</code> section <em>usually</em> contains the programs code i.e. the instructions, the <code>.data</code> sections houses the initialized variables etc.</p> <p>The above rule is merely a convention followed by compilers. In a packed/obfuscated program, the convention may not always hold true. You can have instructions in data segment and vice-versa. This is done for various reasons like thwarting analysis ,disassembly etc.</p> <p>When in Ollydbg you try to set a <code>INT3</code> breakpoint on an instruction that happens to be in a section marked for data, Ollydbg would complain and that is the message you see. </p> <p>The reason for this is suppose that the instruction you set a breakpoint on is actually data. In this case, when the program reads in the value at the address it would read <code>0xCC</code> (INT3 -> 0xCC) instead of the actual value. That can crash the program. Further since this is a read operation, the breakpoint will never be hit.</p> <p>If you want, you may disable the message in Ollydbg options, however doing that is not always recommended. Instead if you are sure that it is an instruction, you may ignore the warning and set the breakpoint.</p> <p>The other way is instead of using a <code>INT3</code> breakpoint, set a Hardware breakpoint (HWBP) on execution at the aforesaid address. This way the program would not crash, even if the hwbp was set on data. HWBP's are enforced my the CPU and does not modify the program in any way unlike <code>INT3</code> breakpoints</p>
4812
2014-07-09T01:59:44.823
<p>I want to set a breakpoint and suddenly the following message appears:</p> <blockquote> <p>You want to place breakpoint outside the code section. INT3 breakpoint set on data will not execute and may have disastrous influence on the debugged program. Do you really want to set breakpoint here?</p> <p>Note: you can permanently disable this warning in Options|Security.</p> </blockquote> <p>Without knowing what that is, I would guess that is not allowed to set the breakpoint. So my question would be:</p> <p>How can I bypass the annoying message? Or better: what must I do to not see this?</p>
Suspicious breakpoint message in ollydbg
|ollydbg|
<p>You can do cat <code>/proc/mtd</code> for the exact "image"</p> <pre><code>cat /proc/mtd dev: size erasesize name mtd0: 01000000 00001000 "whole_flash" mtd1: 00020000 00001000 "bootloader" mtd2: 00060000 00001000 "userconfig" mtd3: 004c0000 00001000 "filesystem1" mtd4: 00300000 00001000 "kernel1" mtd5: 00300000 00001000 "kernel2" mtd6: 004c0000 00001000 "filesystem2" </code></pre>
4817
2014-07-09T09:04:04.573
<p>This is my first attempt at doing some reverse engineering. I'm trying to dump the filesystem off a huawei hg523a TalkTalk router.</p> <p>The problem is its quite limited in the amount of programs that are on the device. Below are a list of programs i can use.</p> <pre><code>BusyBox vv1.9.1 (2012-03-05 00:16:52 CST) multi-call binary Currently defined functions: [, [[, arp, ash, cat, chmod, chown, cp, date, echo, ftpget, ftpput, halt, ifconfig, init, kill, killall, linuxrc, ln, ls, mcast, mkdir, mknod, mount, netstat, nslookup, ping, poweroff, ps, reboot, rm, route, sh, sleep, test, top, traceroute, umount, vconfig, wget </code></pre> <p>So im trying to extract the filesystem to another linux machine so i can go through it more eaisely. I can upload single files with the ftpput command.</p> <pre><code>cat /proc/mtd dev: size erasesize name mtd0: 00010000 00001000 "boot" mtd1: 00001000 00001000 "flag" mtd2: 003c0000 00001000 "main" mtd3: 0002d000 00001000 "config" </code></pre> <p>What im trying to do is upload mtdblock0-3 and then mount this on my other machine to explore the folder structure etc.. It looks like from /proc/mounts that it is a squashfs file system.</p> <pre><code>cat /proc/mounts rootfs / rootfs rw 0 0 /dev/root / squashfs ro 0 0 none /dev tmpfs rw 0 0 /proc /proc proc rw 0 0 none /var tmpfs rw 0 0 none /tmp tmpfs rw 0 0 none /mnt tmpfs rw 0 0 </code></pre> <p>So basically i upload the mtdblock0.</p> <pre><code>ftpput -s -v -u james -p password -l /dev/mtdblock0 -r ftpdir/mtdblock0 192.168.1.64 </code></pre> <p>and mount it on the other computer with:</p> <pre><code>root@kali:~/Desktop/talktalk/blocks# mount -t squashfs mtdblock0 /mnt mount: wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error In some cases useful info is found in syslog - try dmesg | tail or so </code></pre> <p>Could anyone guide me in the right direction as to what i might be doing wrong? So it not possible to transfer the filesystem in this way?</p> <p>thank you in advance for your help.</p>
Dumping firmware through mtdblock device
|firmware|embedded|dumping|
<blockquote> <p>Can we use dynamic analysis (or just emulator) to achieve 100% code coverage?</p> </blockquote> <p>No, if I was right, it equals to Turing Halting problem.</p> <blockquote> <p>emulator based disassemble approach</p> </blockquote> <p>I am afraid this may not be a very new idea, and code coverage is a big issue.</p> <p>But it is always possible that you find a different angle and make some contributions in related area.</p> <p>An interesting paper in last year's tier-one security conference CCS 2013 <a href="https://www.utdallas.edu/~zxl111930/file/CCS13.pdf" rel="nofollow">Obfuscation Resilient Binary Code Reuse through</a> even push related ideas future. </p> <p>It leverages an emulator to disassemble code, dynamic taint analysis to lift concrete value into symbols, and somehow re-use the disassembled asm code (embedded in C code.)</p> <p>I wish it could be helpful</p>
4821
2014-07-10T01:46:17.863
<p>I learned the disassembly challenges from <a href="https://www.usenix.org/legacy/event/usenix03/tech/full_papers/prasad/prasad_html/node5.html" rel="nofollow">this link</a>. The following six challenges are listed in that article:</p> <ol> <li>Data embedded in the code regions</li> <li>Variable instruction size</li> <li>Indirect branch instructions</li> <li>Functions without explicit CALL sites within the executable's code segment</li> <li>Position independent code (PIC) sequences</li> <li>Hand crafted assembly code.</li> </ol> <p>However, I am thinking about the following disassembly method which seems to solve the above challenges. Assuming we have an executable to be disassembled, an input set that can has 100% coverage of the code, and an emulator (e.g. QEMU). Then, we can instrument the emulator to output each instruction executed by the emulated CPU and the corresponding memory address. After that, we can translate each instruction to assembly instruction, and the whole program is now disassembled. </p> <p>Could you please tell me why this idea will not/will work?</p>
Disassemble using an emulator
|disassembly|emulation|
<p>This is quite hard question to answer due to variables within reverse engineering.</p> <p>I would recommend you start off with:</p> <ul> <li>Start game</li> <li>Get some coins or whatever is saved then save the game.</li> <li>Restart the game and get more coins and save the game.</li> <li>Replace the new save with your old file.</li> <li>Does it load? See Answer 1. Otherwise, Answer 2.</li> </ul> <p><strong>Answer 1</strong> Your modified versions of your game files are just in the incorrect format. You will need to some reverse engineering of how the bytes are used within the game. I'd recommend you breakpoint CreateFile and ReadFile and step through your debugger and see how each byte is been read. Ofcourse, this can become a massive task.</p> <p><strong>Answer 2</strong> The game file checksum could be stored somewhere on the file-system or registry to ensure data-integrity of the file. You could use tools such as Process Monitor to help you locate this file or you could set breakpoint on CreateFile and ReadFile and search for it yourself manually. <a href="http://technet.microsoft.com/en-gb/sysinternals/bb896645.aspx" rel="nofollow">http://technet.microsoft.com/en-gb/sysinternals/bb896645.aspx</a></p> <p>Let me know if you get answer 1 or 2 then I can expand my answer in more in-depth details of things you should look out for and so on.</p> <p>I hope this will be a good starting point to your issue.</p>
4824
2014-07-10T03:47:40.887
<p>I recently overwrote the save game file of a video game that my girlfriend and I had been playing through. After trying to recover the file a few different ways (game didn't erase but overwrote the save file), I'm resigned to trying to rebuild the save data manually.</p> <p>I've played with reverse engineering binary executables from crackmes.de in the past with Ollydbg, but this is different and I feel like I'm a bit out of my waters.</p> <p>The game (Sonic All Stars Racing) uses a single .bin file to store records for four in-game accounts. Using a hex editor, pen and paper, I've begun to plot out the file structure and locate offsets for various records.</p> <p>The problem I have is that whenever I make a modification to the file, same size or otherwise, the game declares the save file corrupted and fails to use it. I assume that this is because the game is implementing some form of CRC/checksum on the data to prevent using a corrupted file. (Aside: are CRC and checksum interchangeable terms?)</p> <hr> <p>The game saves the data to a file named <code>"ssr_save.bin"</code> which is responsible for four in-game profiles.</p> <p>What I did was create four different save files by making a backup of the save file after creating each profile.</p> <p>Each file is largely the same. 727040 bytes large. The only difference seems to be the first 12 bytes (0x00 to 0x0B inclusive). These first twelve bytes are completely unique between the four files.</p> <p>There does, however, appear to be more than one data object in that range as there are 3 bytes of zero in the centre of the 12.</p> <pre><code>File 1: 19 8E 0B 60 13 00 00 00 F9 3E 00 B0 File 2: 93 7B 0F 36 13 00 00 00 B6 35 02 9B File 3: 69 71 1B 14 13 00 00 00 A1 30 08 8A File 4: D9 47 32 E8 13 00 00 00 D9 9B 13 74 </code></pre> <p>What I'm trying to figure out is what these bytes represent and how I can manipulate them to let me modify the body of the save data and not throw the corruption error in the game.</p> <p>Can anyone help me find out how the game is checksumming the file and reverse engineer the process so I can create a valid file?</p> <p><a href="https://dl.dropboxusercontent.com/u/303145/savefiles.zip" rel="nofollow">Here is an archive of the four save-data files</a></p> <p>Troy.</p>
Modifying a binary save-data file for a video game with a CRC/Checksum check
|binary-analysis|static-analysis|hex|cryptography|
<p>There is virtually no difference between the bytecode emitted by <code>loadfile</code> and <code>luac</code>. The only possible reason for the error you are getting is that you are opening the file <em>stringdumped.txt</em> in text mode. Try the following code and see if there are any errors</p> <pre><code>f = io.open("stringdumped.txt", "wb") --Note that file is opened in binary mode f:write(string.dump(loadfile("sample.lua"))) f:close() </code></pre> <p>Since there is no difference, the output file <em>stringdumped.txt</em> can both be run by the lua interpreter as well as decompiled by <em>unluac</em>. The reversing steps too are exactly similar as you would do with any other compiled lua scripts.</p>
5827
2014-07-10T12:54:08.977
<p>I've been experimenting with decompiling Lua bytecode and found useful tools like unluac, and LuaAssemblyTools. Unluac seems to do the trick with lua scripts compiled with luac giving me almost the exact source code, however when I convert lua script to bytecode using the code:</p> <pre><code>file:write(string.dump(loadfile(filename))) </code></pre> <p>I get a different output than with luac, however they are very much the same being only a byte extra at (a lot of) different places. Now this new file will give me an <code>IllegalState exception</code> from unluac and when I try to run the bytecode file (created by the code line above) in luac with the -l option I get:</p> <pre><code>C:\MyDir&gt;luac -l stringdumped.txt luac: stringdumped.txt: bad integer in precompiled chunk </code></pre> <p>So there is clearly a difference between <code>string.dump</code> and luac, even though it is suggested here: <a href="http://lua-users.org/wiki/LuaCompilerInLua" rel="nofollow">http://lua-users.org/wiki/LuaCompilerInLua</a> to use <code>string.dump</code> as an emulator for luac.</p> <p>Could anyone explain the difference to me, and suggest how I would go about reversing a <code>string.dump</code> "compiled" script?</p>
Decompiling/disassembling lua bytecode
|disassembly|decompile|byte-code|
<p>Generally, the solutions to this problem can be classified to:</p> <ul> <li><p>Pattern matching heuristics. Just like what you are proposing. For example, searching for <code>push</code>es in the binary can provide a (rather) rough approximation of function starts. Things are more difficult if you want to locate function ends though.</p></li> <li><p>Machine learning. Pattern matching can be automated using machine learning. There are several proposals in the literature like [<a href="https://www.aaai.org/Papers/AAAI/2008/AAAI08-127.pdf" rel="nofollow noreferrer">1</a>], [<a href="https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-bao.pdf" rel="nofollow noreferrer">2</a>], and [<a href="https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-shin.pdf" rel="nofollow noreferrer">3</a>]. All of which attempt to learn byte-level features of function starts and ends. However, modern compiler optimizations make it challenging for such approaches to generalize to binaries beyond the training set.</p></li> <li><p>CFG-based techniques. This is the most promising approach based on [<a href="https://doi.org/10.1145/2968455.2968505" rel="nofollow noreferrer">4</a>] (disclosure: first author here) and concurrently [<a href="https://doi.org/10.1109/EuroSP.2017.11" rel="nofollow noreferrer">5</a>]. Basically, it proceeds with (1) direct call target analysis, (2) CFG traversal to locate function ends, and (3) tail-call target analysis.</p></li> <li><p>Call frame information (CFI) records. Before doing anything fancy, checkout the CFI records in the <code>.eh_frame</code> section. There is a good chance that functions are defined there already. In order to dump CFI records, you can use something like <code>readelf --debug-dump=frames /bin/ls</code>.</p></li> </ul> <p>I've recently revisited the problem of function identification in this blog <a href="https://blog.formallyapplied.com/2020/05/function-identification/" rel="nofollow noreferrer">post</a> where I provide more details.</p>
5830
2014-07-10T17:44:34.873
<p>I am trying to generate a <em>coarse-grained</em> Call Graph based on some assembly code disassembled from binary on x86 32 bit platform.</p> <p>It is very hard to generate a precise Call Graph based on asm code, thinking of various indirect control flow transfer, so right now I <strong>only consider direct control flow transfer</strong>.</p> <p>So firstly I am trying to identify <code>functions</code> (begin and end addresses) in the disassembled assembly code from a <strong>stripped</strong> binary on x86, 32bit.</p> <p>Right now, my plan is somehow like this:</p> <p>As for the begin addresses, I might conservatively consider any assembly code looks like this</p> <pre><code> push %ebp </code></pre> <p>indicates the beginning address of a function.</p> <p>and also, I might scan the whole problem, identifying all the <code>call</code> instruction with the destination, the consider these function call's destinations as all the function begin address</p> <p>The problems are:</p> <ol> <li><p>some of the functions defined in a binary might never be called.</p></li> <li><p>some of the <code>call</code> has been optimised as <code>jump</code> by compiler (thinking of tail recursive call)</p></li> </ol> <p>As for the end address, things become more tricky because multiple <code>ret</code> could exist in one single function...</p> <p>So I am thinking that I might conservatively consider the range between any nearest <strong>function begin addresses</strong>, as one function..</p> <p>Am I right? Is there any better solution..?</p>
How to identify functions in a stripped binary on x86 32bit?
|disassembly|assembly|binary-analysis|static-analysis|
<p>Since you're not reading <code>a</code> anywhere, it seems gcc doesn't even bother reading it from the stack, and creates a local variable for it. Try replacing the <code>a=5</code> with <code>a+=5</code>, so the compiler has to read the variable, and the instruction will probably be changed to access [ebp+8], which is where the parameter should be stored.</p> <p>The reason for this behaviour <em>might</em> be that gcc tries to make the 32 bit code generation more similar to the 64 bit version, where parameters are passed in registers, and need to be saved <em>below</em> the stack pointer if the compiler needs the register, or a pointer to the parameter needs to be created. Doing the same in 32 bit - at least sometimes - might help the developers share code between the 32- and 64 bit optimizers.</p>
5834
2014-07-11T16:33:41.737
<p>I compiled the following program using gcc version 4.6.3 on Ubuntu 32bit with the command <code>gcc -ggdb -o test test.c</code></p> <pre><code> void test(int a, int b, int c, int d) { int flag; char buffer[10];<br /> flag = 31337; buffer[0] = 'a'; a = 5; } int main(void) { test(1, 2, 3, 4); return 0; } </code></pre> <p>The disassembly of the above test function in gdb is :- <pre><code> 0x08048404 &lt;+0>: push ebp 0x08048405 &lt;+1>: mov ebp,esp 0x08048407 &lt;+3>: sub esp,0x28 0x0804840a &lt;+6>: mov eax,gs:0x14 0x08048410 &lt;+12>: mov DWORD PTR [ebp-0xc],eax 0x08048413 &lt;+15>: xor eax,eax 0x08048415 &lt;+17>: mov DWORD PTR [ebp-0x20],0x7a69 0x0804841c &lt;+24>: mov BYTE PTR [ebp-0x16],0x41 => 0x08048420 &lt;+28>: mov DWORD PTR [ebp-0x1c],0x5 0x08048427 &lt;+35>: mov eax,DWORD PTR [ebp-0xc] 0x0804842a &lt;+38>: xor eax,DWORD PTR gs:0x14 0x08048431 &lt;+45>: je 0x8048438 0x08048433 &lt;+47>: call 0x8048320 &lt;__stack_chk_fail@plt> 0x08048438 &lt;+52>: leave 0x08048439 &lt;+53>: ret </pre></code></p> <p>As much as I know, the assembly instruction after arrow corresponds to the C instruction <code>a = 5;</code> in test function. So the address <code>[ebp-0x1c]</code> should represent the address of variable <code>a</code>.<br /> But the address that <code>[ebp-0x1c]</code> represents is <code>0xbffff2bc</code> and the address of variable <code>a</code> is <code>0xbffff2e0</code>.<br /> I don't understand how both addresses can be different. Is this some kind of optimization done by gcc?<br /></p>
gcc storing value of a variable at a different location
|disassembly|
<p>IDA Pro is no magic tool to automatically decompile binaries to their source code. The decompiler output should not be relied every time (as compiling leads to loss of information) although IDA boasts of the finest decompiler available. Instead focus on the disassembly listing. For specific parts, you can use the decompiler output as your reference.</p> <p>Deobfuscation is a multi-step process. First try to understand the usages of <em>variables</em>, <em>structures</em>, etc and then give them a more easy-to-understand names reflecting their purpose. In many cases you can understand the variables purposes by just noting how it is used in function calls. For example <code>Vcl.Controls.TControl.GetTextLen</code> returns the length of the control's text. That means among the parameters passed, one must be the a pointer to the <code>TControl</code>. You can use this information to rename variables.</p> <p>In case of <code>VCL</code> binaries, <em><a href="http://kpnc.org/idr32/en/" rel="nofollow">Interactive Delphi Reconstructor</a></em>, will give you more easy-to-understand disassembly, as it is geared for that purpose. IDR also has a somewhat very limited decompilation capability.</p> <p>For better understanding IDA Pro and its myriad of features, I would recommend to go through these two books <em><a href="http://rads.stackoverflow.com/amzn/click/1593272898" rel="nofollow">The IDA Pro Book</a></em> and <em><a href="http://rads.stackoverflow.com/amzn/click/159749237X" rel="nofollow">Reverse Engineering Code with IDA Pro</a></em> </p>
5839
2014-07-13T01:42:04.520
<p>I have wanted to get into the art of reverse engineering for quite some time now, so I took a look at a few online lessons (such as opensecuritytraining.info) and also got my hands on IDA Pro.</p> <p>Obviously, since this is a complex topic, I was overwhelmed by registers, pointers, instructions et cetera. I know assembler and C fairly well, it's just (like I said earlier) a topic where you have to learn much.</p> <p>Now to my actual question: I have downloaded a "CrackMe"-Program and started debugging it. Basically the objective is to find a key which you then have to enter into a Textbox in the program. I found the key checking function fairly easily and identified some logic, but I can't wrap my head around how the program actually compares the string. My C skills are much greater than my Assembler skills, so I decided to get some Pseudocode printed. The problem is that the Pseudocode is pretty messy (I'm guessing that's because of compiler optimizations) and I basically can't understand what this piece of code is supposed to do.</p> <p>Here is the code (sorry it's a bit long):</p> <pre><code>int __usercall TSDIAppForm_Button1Click&lt;eax&gt;(int a1&lt;eax&gt;, int a2&lt;ebx&gt;, int a3&lt;edi&gt;, int a4&lt;esi&gt;) { int v4; // ebx@1 int v5; // esi@1 int v6; // eax@1 signed int v7; // eax@3 signed int v8; // edx@3 int v9; // ebx@3 int v11; // edx@12 int v12; // [sp-24h] [bp-34h]@1 int (*v13)(); // [sp-20h] [bp-30h]@1 int *v14; // [sp-1Ch] [bp-2Ch]@1 int v15; // [sp-18h] [bp-28h]@1 int (*v16)(); // [sp-14h] [bp-24h]@1 int *v17; // [sp-10h] [bp-20h]@1 int v18; // [sp-Ch] [bp-1Ch]@1 int v19; // [sp-8h] [bp-18h]@1 int v20; // [sp-4h] [bp-14h]@1 int v21; // [sp+0h] [bp-10h]@1 int v22; // [sp+4h] [bp-Ch]@1 int v23; // [sp+8h] [bp-8h]@2 void (__fastcall *v24)(int); // [sp+Ch] [bp-4h]@7 int v25; // [sp+10h] [bp+0h]@1 v22 = 0; v21 = 0; v20 = a2; v19 = a4; v18 = a3; v5 = a1; v17 = &amp;v25; v16 = loc_45C6FD; v15 = *MK_FP(__FS__, 0); *MK_FP(__FS__, 0) = &amp;v15; JUMPOUT(Controls__TControl__GetTextLen(*(_DWORD *)(a1 + 872)), 0xFu, *(unsigned int *)"j"); v6 = Controls__TControl__GetTextLen(*(_DWORD *)(a1 + 872)); System____linkproc___DynArraySetLength(v6); System____linkproc___DynArraySetLength(664); v14 = &amp;v25; v13 = loc_45C699; v12 = *MK_FP(__FS__, 0); *MK_FP(__FS__, 0) = &amp;v12; v4 = 0; do { Controls__TControl__GetText(*(_DWORD *)(v5 + 872), &amp;v21, v12); *(_DWORD *)(v23 + 4 * v4) = *(_BYTE *)(v21 + v4 - 1); ++v4; } while ( v4 != 16 ); v8 = 1; v9 = 0; v7 = 4585384; do { if ( v8 == 16 ) v8 = 1; *(_BYTE *)(v22 + v9++) = *(_BYTE *)v7++ ^ *(_BYTE *)(v23 + 4 * v8++); } while ( v9 != 665 ); v24 = (void (__fastcall *)(int))v22; // I know the key to success lies here, but I can't figure out what this if is supposed to do if ( *(_BYTE *)v22 != 96 || *(_BYTE *)(v22 + 4) != 208 || *(_BYTE *)(v22 + 9) ) MessageBoxA_0(0, "Invalid Key", "Error", 0); else v24(v22); *MK_FP(__FS__, 0) = v12; v11 = v15; *MK_FP(__FS__, 0) = v15; System____linkproc___LStrClr(&amp;v21, v11, 4572932); System____linkproc___DynArrayClear(&amp;v22, off_45C568); return System____linkproc___DynArrayClear(&amp;v23, off_45C548); } </code></pre> <p>I would appreciate it if someone could give me advice on how to "deobfuscate" this piece of code. Are there any plugins available to do this? Is there a special technique that I can use to figure it out? Would it be better to look at the Assembler code instead of the Pseudocode?</p> <p>I especially wonder where these weird constants (like 872 for example) come from.</p> <p>Answers would be highly appreciated.</p>
Deobfuscating IDA Pseudocode
|ida|decompilation|deobfuscation|
<p>Today, several years after the original post and answers - There's another noteworthy package for generating machine code from assembly- <a href="https://www.keystone-engine.org/" rel="nofollow noreferrer">Keystone</a>.</p> <p>Keystone is written in C++ but has binding for many languages (Python included), and supports multiple architectures (including x86, amd64 and ARM) so it's a perfect fit!</p> <p>Quoting the website's highlighted features:</p> <blockquote> <ol> <li>Multi-architecture, with support for Arm, Arm64 (AArch64/Armv8), Ethereum Virtual Machine, Hexagon, Mips, PowerPC, Sparc, SystemZ, &amp; X86 (include 16/32/64bit).</li> <li>Clean/simple/lightweight/intuitive architecture-neutral API.</li> <li>Implemented in C/C++ languages, with bindings for Java, Masm, Visual Basic, C#, PowerShell, Perl, Python, NodeJS, Ruby, Go, Rust, Haskell &amp; OCaml available.</li> <li>Native support for Windows &amp; *nix (with Mac OSX, Linux, *BSD &amp; Solaris confirmed).</li> <li>Thread-safe by design.</li> <li>Open source.</li> </ol> </blockquote> <p>Keystone is part of a more extensive set of tools together with <a href="https://www.capstone-engine.org/" rel="nofollow noreferrer">Capstone</a> (Disassembler) and <a href="https://www.unicorn-engine.org/" rel="nofollow noreferrer">Unicorn</a> (Emulator).</p> <p>Additionally, if you just want something quick and easy (and don't mind using an online service) - shell-storm's <a href="https://shell-storm.org/online/Online-Assembler-and-Disassembler/" rel="nofollow noreferrer">online dis/assembler</a> is also based on Keystone and Capstone</p>
5841
2014-07-13T08:27:18.583
<p>It would be very useful to have a pure Python library that could assemble x86, x64, and ARM instructions. Do you have a recommendation?</p> <p>I don't mind if they are not pure Python, but that'd be preferred.</p>
Python library for assembling x86, x64 and ARM exploits
|disassembly|assembly|python|
<p>Use a current. up to date version of binwalk, it works fine </p> <pre><code>$ binwalk rssflash_1035_201311211539.update00.bin DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 Squashfs filesystem, little endian, version 4.0, compression:gzip, size: 83899310 bytes, 3291 inodes, blocksize: 131072 bytes, created: Fri Nov 22 00:48:15 2013 </code></pre> <p>Or you can use Firmware Mod Kit's <code>unsquash-all</code> to unsquash it. </p>
5846
2014-07-14T02:28:15.467
<p>While poking around at the headers and such from my new Simple.TV DVR, I found it downloading a file named rssflash_1035_201311211539.update00.bin. I ran binwalk to look for anything obvious, but it came up blank. I suspect it might be encrypted (?). Any thoughts about what I could do next to get more information about this?</p> <p>The download link to the file, in case anyone else is interested: [redacted]</p> <p>Thanks!</p>
I found the .bin firmware for my Simple.TV device. Binwalk comes up blank. Anything I can do?
|firmware|
<p>When I was learning RE (and I'm always still learning!), I found reading <a href="http://www.charlespetzold.com/code/" rel="nofollow noreferrer">"CODE" by Charles Petzold</a> to be extremely informative and really helped me understand WHY computers work the way that they do on a low level. <a href="http://www.microsoft.com/mspress/books/sampchap/4677.aspx" rel="nofollow noreferrer">Sample chapter available here</a>.</p> <p>It's a book about first principles, but reads like a fiction book, not a computer science book. At one point Petzold walks the reader through how to build a computer counting machine using only parts that would've been available ~100 years ago. If you've never taken an electronics class and concepts such as gates and boolean logic aren't very clear, start here. You'll learn about these concepts without even realizing it.</p> <p>After reading that (which you can finish in a couple evenings), then you could move on to GDB. I'm sure others can make better recommendations than me on GDB, but I found this book helpful the times I've used GDB: <a href="http://shop.oreilly.com/product/9781593271749.do" rel="nofollow noreferrer">The Art of Debugging with GDB and DDD</a></p> <p>To answer the question about registers, I think an image can make this most clear. Note that this only covers 32-bits, but should be easy enough to see how the 64-bit registers expand on this.</p> <p><img src="https://i.stack.imgur.com/fXjfs.png" alt="enter image description here"> source: <a href="http://www.cs.virginia.edu/~evans/cs216/guides/x86.html" rel="nofollow noreferrer">http://www.cs.virginia.edu/~evans/cs216/guides/x86.html</a></p>
5847
2014-07-14T02:35:37.890
<p>I am somewhat interested in learning how to RE but right now am learning C, and was wondering if anyone could give me a link to a good tutorial on how to use <code>gdb</code></p> <p>Also, in reference to registers...if <code>rax</code> is 64-bit and <code>eax</code> is 32, then <code>ax</code> must be 16, right? What's 8bit...or was 8bit ASM not a thing?</p>
Learning disASM, other things
|gdb|
<p>I think the c++ code would look something like this:</p> <pre><code>// has vtbl struc_13_vtable // has constructor struc_13_ctor struct struc_13 { int a,b; short c,d; int e,f; struc_13(short x) : a(0), b(0), c(x), d(0), e(0), f(0) { } virtual void someotherfn(); }; // has vtbl off_12C057C // has inlined constructor struct derivedmember : struc_13 { derivedmember() : struc_13(0x30) { } virtual void someotherfn(); }; // has vtbl off_12C0680 // has constructor sub_106C0A0 struct A { derivedmember member; virtual void somefn(); }; </code></pre>
5849
2014-07-14T05:55:06.107
<p>I was reversing some C++ code and encountered following function.</p> <pre><code>sub_106C0A0 proc near var_10= dword ptr -10h var_C= dword ptr -0Ch var_4= dword ptr -4 push 0FFFFFFFFh push offset SEH_106C0A0 mov eax, large fs:0 push eax mov large fs:0, esp push ecx push esi mov esi, ecx push edi lea edi, [esi+4] push 30h mov ecx, edi mov [esp+1Ch+var_10], esi mov dword ptr [esi], offset off_12C0680 call struc_13_ctor mov dword ptr [edi], offset off_12C057C ; another vtable init ? </code></pre> <p>This function passes this pointer of some object (struc_13), which is esi+4, to the struc_13_ctor. Inside the struc_13_ctor function, it initializes the vtable pointer and other member variables. </p> <pre><code>; int __thiscall struc_13_ctor(struc_13 *this, __int16 a2) struc_13_ctor proc near arg_0= word ptr 4 mov dx, [esp+arg_0] mov eax, ecx xor ecx, ecx mov dword ptr [eax], offset struc_13_vtable mov [eax+4], ecx mov [eax+8], ecx mov [eax+0Ch], dx mov [eax+0Eh], cx mov [eax+14h], ecx mov [eax+10h], ecx retn 4 struc_13_ctor endp </code></pre> <p>However after returning from struc_13_ctor, it overwrites the vtable pointer with the new value, which is off_12C057C in this case. </p> <pre><code>call struc_13_ctor mov dword ptr [edi], offset off_12C057C ; another vtable init ? </code></pre> <p>I have seen this kind of behaviors a lot while looking at ctor functions, but never understood why this happens. </p>
Questions about reversing object oriented code(initializing vtables in ctors)
|c++|
<p><strong>Update:</strong> Admirably, after just a few days after I sent in a request to include a feature to send input to command line applications, the sole developer of Hopper disassembler has included the feature. Notice the new 'application output' tab in the new Hopper disassembler 3.3.3:</p> <p><img src="https://i.stack.imgur.com/0ltS7.png" alt="enter image description here"></p>
5851
2014-07-14T13:00:56.863
<p>To test the debugging capabilities of Hopper, I wrote a simple C++ command line application, and tried to run it on the remote debugging server (with gdb). However, I learned after I failed to be able to interact with the application, from the author, that the Hopper server does not support CL apps currently. In other words, it seems the app has to have its own GUI.</p> <p>Are there any workarounds for this? Specifically, is there a way I can write a standalone C++ Mach-O executable which has its own version of terminal built into it (without all the features, just an interpreter)?</p>
Interacting with command line programs in Hopper disassembler (Mac OS 10.9)
|debuggers|c++|hopper|mach-o|
<p>You need debugging symbols for the variable names to be defined in GDB. Did you compile with the <code>-g</code> switch?</p>
5855
2014-07-14T19:11:26.170
<p>I am getting the following from gdb:</p> <p><img src="https://i.stack.imgur.com/zdqdQ.png" alt="enter image description here"> </p> <p>Below is the source of the program and the tutorial it came from. BAsed on what is going on in the tutorial, I should not be getting an error.</p> <pre><code>int main() { int a = 5; int b = a + 6; return b; } </code></pre> <p><a href="https://www.hackerschool.com/blog/7-understanding-c-by-learning-assembly" rel="nofollow noreferrer">https://www.hackerschool.com/blog/7-understanding-c-by-learning-assembly</a></p>
Why can't gdb find the address of a stack variable
|gdb|
<blockquote> <p>I tried to change binary 6A 01 to 6A A2 which should change to 162 (turkish charset) but instead turned to negative value.</p> </blockquote> <p>Usually <a href="http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html?iid=tech_vt_tech+64-32_manuals" rel="nofollow">the instruction set reference</a> is a huge help if you don't understand how instructions behave. In this case, I'd say you will need to use <code>68</code> (<code>PUSH imm32</code>) instead of <code>6A</code> (<code>PUSH imm8</code>). The <code>imm8</code> is sign-extended when pushed onto the stack. Note that you'll have to either shift the following function code by 3 bytes (which are the difference in sizes between <code>imm32</code> and <code>imm8</code> operands). Depending on the compiler used, its options, and the function size, there may be pad bytes after the function which can be used exactly for that. Watch out for e.g. jump tables, if there are any -- they may need to be patched as well.</p> <p>If it is not possible to shift the code, you can make use of code space somewhere else in the executable -- usually, the last page in <code>.text</code> is not fully used; move instructions that do not fit there and make a jump, like:</p> <pre><code>... PUSH EDI PUSH EDI PUSH A2 ; Your patched insn; 5 bytes ... PUSH 190 PUSH EDI PUSH EDI ; So we need 2 extra bytes here ; Moving CALL gives 6, patched PUSH takes 3, patched JMP takes 5 ; Moving two PUSHes along with CALL solves the problem JMP _somewhere_ ; Takes 5 bytes, opcode E9 disp32 PUSH Game5_4.... ; back is here </code></pre> <p>And then, in the newly coded part (<code>_somewhere_</code>):</p> <pre><code>PUSH EDI PUSH EAX CALL DWORD PTR DS:[&lt;&amp;GDI32.CreateFontA&gt;] JMP back </code></pre> <blockquote> <p>Is changing <code>CP_ACP</code> to <code>CP_UTF8</code> gonna work ?</p> </blockquote> <p>I don't know, to be honest. Depends a lot on other code. Making the program support something it was not designed for is a big ordeal. It might work, it might not, it might end up being buggy.</p>
5864
2014-07-15T16:52:30.820
<p>I dont have any experience with assembler or reversing code. I need to change charset of .exe program to support turkish characters. I have opened it in Ollydbg do some tests. </p> <p><img src="https://i.stack.imgur.com/pK8V6.png" alt="enter image description here"></p> <p>There are several blocks like this. I tried to change binary <code>6A 01</code> to <code>6A A2</code> which should change to <code>162</code> (turkish charset) but instead turned to negative value. Also there are some codes like this one. Is changing <code>CP_ACP</code> to <code>CP_UTF8</code> gonna work ? </p> <p>Either way, is it possible to edit like this and get program support charset ?</p> <p><img src="https://i.stack.imgur.com/yDc1D.png" alt="enter image description here"> </p>
Change program's codepage / charset
|disassembly|ollydbg|
<p>If you're looking to find the base address of a segment based on its selector, you can use <code>dg</code><em><code>&lt;selector&gt;</code></em>; in this context you would use <code>dg fs</code>:</p> <pre><code>0:000&gt; dg fs P Si Gr Pr Lo Sel Base Limit Type l ze an es ng Flags ---- -------- -------- ---------- - -- -- -- -- -------- 003B 7ffdf000 00000fff Data RW Ac 3 Bg By P Nl 000004f3 </code></pre> <p>You can see above that the <code>Base</code> of <code>fs</code> is <code>7ffdf000</code>, so <code>FS:[0] == [7ffdf000]</code>.</p> <pre><code>0:000&gt; db 7ffdf000 7ffdf000 1c f7 1d 00 00 00 1e 00-00 f0 1c 00 00 00 00 00 ................ 7ffdf010 00 1e 00 00 00 00 00 00-00 f0 fd 7f 00 00 00 00 ................ 7ffdf020 0c 13 00 00 bc 0f 00 00-00 00 00 00 2c f0 fd 7f ............,... 7ffdf030 00 a0 fd 7f 00 00 00 00-00 00 00 00 00 00 00 00 ................ 7ffdf040 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 7ffdf050 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 7ffdf060 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 7ffdf070 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ </code></pre>
5868
2014-07-16T01:21:22.707
<p>It seems that Windows 8 broke Ollydbg as several <code>ntdll</code> functions keep throwing exception <code>0xC0000008</code> and crashing my debugger.</p> <p>I am now using Windbg. But, I am unable to view <code>FS</code> (specifically <code>FS:[0]</code>). How can I get a dump of <code>FS</code> via Windbg? I've tried googling to no avail. I am specifically interested in SEH, but all I can find is dumping TEB or PEB.</p>
How can I view FS:[0] with windbg?
|x86|windbg|
<p>After loading the main dump into IDA, in IDA's menubar go to <code>File</code> → <code>Load file</code> → <code>Additional binary file...</code>, select the dump of the dynamically allocated memory, and specify the dynamic allocation address as the <code>Loading segment</code>.</p>
5874
2014-07-16T16:41:25.980
<p>I'm debugging a process inside a VM via Olly, and occasionally exporting a section dump when needed and loading it on the host system for better analysis.</p> <p>Right now I'm looking at a dump of a certain code section that's referencing function calls in another, dynamically allocated, section. In the debugger I can of course see all the function calls, but in IDA all I have are calls to immediate addresses that don't exist.</p> <p>I'd like to be able to dump the referenced section and somehow bluntly attach it to the same .idb so IDA would be able to resolve the references for me.</p> <p>I couldn't find anything about it on google or when digging around the menus. Did I miss something or is this impossible or requires an addon? It's also possible for me to write an idapython script that defines and copies the section over, but I don't see any relevant API calls.</p> <p>Debugging via IDA and taking a full memory snapshot is a solution I'd like to not have to use; I enjoy using olly.</p>
Adding another section to an idb file
|ida|
<p>To save and restore your VM's state, use snapshots: <a href="http://www.virtualbox.org/manual/ch01.html#snapshots" rel="nofollow noreferrer">http://www.virtualbox.org/manual/ch01.html#snapshots</a></p> <blockquote> <p>With snapshots, you can save a particular state of a virtual machine for later use. At any later time, you can revert to that state, even though you may have changed the VM considerably since then. A snapshot of a virtual machine is thus similar to a machine in "saved" state, as described above, but there can be many of them, and these saved states are preserved.</p> </blockquote> <p><img src="https://i.stack.imgur.com/k2Y4g.png" alt="VirtualBox Snapshots"></p> <p>Please create a separate Stack Exchange question for your second question.</p>
5876
2014-07-16T18:20:49.473
<p>I'm running two virtual machines with Windows 7 (host OS Mac) using Virtualbox which I'd like to use to analyze malware. I have configured Visual Studio debugging and WinDBG, as well as other tools.</p> <p>What's the best way to save a backup of the victim machine to quickly recover from damage caused by malware? Should I make a .zip of the entire Virtualbox folder and store it elsewhere?</p> <hr> <p>Additional question: is it safe to run malware on a virtual machine with bridged adapter network settings for VS remote debugging?</p>
Setting up virtual machine to recover from malware
|debugging|virtual-machines|
<p>In C pseudocode let's say you have a function called <code>doJob</code>. You want to create a thread to executes it.</p> <pre><code>DWORD WINAPI doJob(LPVOID lpParameter){ // Do some work. You can only pass one parameter. // If you need more parameters, define a structure // and send it though it's pointer. return statuscode; } Handle hThread = CreateThread(&amp;attributes,dwStackSize,&amp;doJob,&amp;paramstruct,flags,&amp;newThreadIdBuffer); </code></pre> <p>Or in asm (nasm syntax, if I still remember it):</p> <pre><code>lea eax, newThreadIdBuffer push eax push 0 ; or 4 or 0x00010000 or 0x00010004 lea eax, paramstruct push eax lea eax, doJob push eax push dwStackSize ; 0 will use default lea eax, attributes push eax call CreateThread </code></pre> <p>This can be done cleaner, but I believe it demonstrates the concept.</p>
5880
2014-07-16T23:03:35.030
<p>I have the following assembly code :</p> <pre><code>..... lea eax, [ebp+ThreadID] push eax ; lpThreadID push 0 ; dwCreationFlags push 0 ; lpParameter push offset StartAddress ; lpStartAddress push 0 ; dwStackSize call CreateThread .... </code></pre> <p>So, I try to translate it in a C-like pseudocode:</p> <pre><code>DWORD* LPWORD eax_lpThreadID = NULL; DWORD dwCreationFlags; void *LPVOID lpParameter; SIZE_T dwStackSize; LPSECURITY ATTRIBUTES lpThreadAttributes; HANDLE handle_to_new_Thread = CreateThread(lpThreadAttributes, dwStackSize, ..., lpParameter, dwCreationFlags, eax_lpThreadID ); </code></pre> <p>As you can see, I do not include the 3rd parameter, namely the parameter <code>LPTHREAD_START_ROUTINE lpStartAddress</code>, because I have problems understanding it. In <a href="https://stackoverflow.com/questions/19472837/what-is-a-lpthread-start-routine">this SO thread</a> i have read that a <code>LPTHREAD_START_ROUTINE</code> is a function pointer defined as:</p> <pre><code>typedef DWORD (__stdcall *LPTHREAD_START_ROUTINE) ( [in] LPVOID lpThreadParameter ); </code></pre> <p>That would mean that the 4th parameter <code>lpThreadParameter</code> is a parameter of this. But how can I integrate that information into my pseudo C code program ? I am little bit confused about that. Can someone explain it to me? The other attributes/parameters are clear.... </p>
How to understand the "lpStartAddress"-Parameter of the function CreateThread
|assembly|c|
<p>Here is a hack for now... I think it would be better to not allow for it to make backups... Which I can do but for now this will just allow the changes to take place and JMP over the error sequence.</p> <p>The Origional</p> <pre><code>OFFSET 004BDBF7 :JNZ SHORT 004BDC1B </code></pre> <p>Change to:</p> <pre><code>JMP 004BDC1B </code></pre> <p>I almost feel bad for this cause there is has to be an option somewhere that I am not seeing. Not to mention the whole inception feeling of debugging a debugger running another process. 0.o...</p>
5881
2014-07-16T23:40:44.830
<p>I have been looking all around for an answer to this, so I am hoping I find an answer here.</p> <p>I am working in Ollydbg 2.1 and every time I patch an exe it makes a foo.bak (backup) which is ok. However, I must reload the program to make more patches and often I am making multiple patches in multiple stubs at a time. Olly wont allow me to patch multiple times unless I rename the file cause there is a .bak already there and it wont over write that. I keep all my own backups so I am wondering.</p> <p>1 Is there a way to have olly not make backups?<br> 2 Is there a way to have olly allow forover writing the .bak files or some way to have multiple saves in a session?</p> <p>Please let me know . </p> <p>Thanks!</p>
Ollydbg 2.1 Allow for multiple saves or not make backups
|ollydbg|patching|
<p>Hard to tell what the reason for the differences might be without actually seeing the differences, but one guess is that you're doing <code>ReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read)</code>, while the other tool may be doing <code>foreach(section) {ReadProcessMemory(hProcess, header32.ImageBase + section.RVA, buffer, section.VirtualSize, bytes_read)}</code>; this may cause the "caves" between sections to differ.</p> <p>(BTW, I assume your <code>header32.ImageBase</code> is the actual base address of the module in memory, not just the image base address from the PE headers, since ASLR could relocate it at runtime.)</p>
5889
2014-07-18T07:34:41.780
<p>Since I love to play with the WinAPI or debugging in general, I decided to write a small unpacker for the open source PE executable packer <a href="http://upx.sourceforge.net/" rel="nofollow">UPX</a> today (Windows version).</p> <p>In order to accomplish this, I proceeded as follow:</p> <ul> <li><code>CreateProcess</code> API all with <code>DEBUG</code> and <code>DEBUG_ONLY_THIS_PROCESS</code> flags.</li> <li><code>GetThreadContext</code> API call in order to read value of <code>EIP</code>.</li> <li><code>ReadProcessMemory</code> API call loop searching for the last <code>JMP</code> instruction.</li> <li>Overwriting the <code>E9</code> with <code>CC</code> in order to set an <code>INT3</code> breakpoint on the address.</li> <li>Entering <code>DebugEvent</code> loop waiting for the breakpoint. Once reached, reset byte back to <code>E9</code>, decrease <code>EIP</code> by one and jump to the address (<code>OEP</code>) of the target.</li> </ul> <p>After reaching the <code>OEP</code>, I proceed as follows in order to dump the process:</p> <ul> <li>Read ImageBase, Base of code, ImageSize, ... from original PE headers</li> <li><code>ReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read)</code></li> <li>Save buffer content to payload.bin, update the PE header of the file with new EntryPoint (<code>OEP</code>) and set <code>RawDataOffset</code> and <code>RawDataSize</code> of each section to its corresponding <code>VirtualAddress</code>/<code>VirtualSize</code>.</li> </ul> <p>After creating the dump with fixed <code>OEP</code> &amp; RAW offsets/sizes for the sections, I fix the dump with ImpREC (right now manually, but I plan to use <code>ImpREC.dll</code> or the ImpREC lite source in order to assemble everything in one tool at a later point).</p> <p>The thing that confuses me though, is the fact, that the resulting binaries worked perfectly fine (exact match with the MUP) for one test case (a small hello world fasm application) and my dump file was exactly the same I had received through OllyDump, but when I tried to do the same unpacking with an UPX packed version of <code>putty.exe</code>, my dumped memory varied from the one OllyDump had dumped starting at RAW offset <code>0x73970</code> (exact match before that address). </p> <p>However - the file size is again the same one (and all bytes before that offset match), just after that certain address the bytes magically won't match anymore (they are still non-zero though).</p> <p>I studied the source code in <code>OllyDump.c</code> thoroughly regarding this difference, but as for now I didn't find my mistake... In some cases my dumps are equal to the ones generated by OllyDump and in some they aren't. Or is the mistake probably in my approach already?</p> <p><strong>Note:</strong> Source code omitted on purpose, since it's a few hundred lines long and super messy as for now. Can/will add further details if required or if I missed something, please just let me know in the comments.</p>
An issue when unpacking UPX
|unpacking|dumping|upx|
<p>No, this is not a bug. Likely this is because you confuse the executable's entry point address (where Olly breaks) with the address of your <code>main()</code> function (where you expect it to break). You should locate your <code>main()</code> and set a breakpoint there manually instead.</p> <p>There is a lot going on behind the scene before execution flow reaches <code>main()</code>. The code that gets control first is hidden within the C Run-Time (CRT) library provided by your compiler and is linked in automatically when you link your executable. This code (aptly named CRT startup) is responsible for setting up various things when a C program starts up, mainly, initializes all the internals of the C runtime (there is a lot of other stuff which I won't mention here), performs C++ static objects' constructor calls, and at the end calls your <code>main()</code>. So to get things going, the linker sets up the entry point to inside this startup machinery, which is exactly what we observe.</p> <p>Note: It is possible to strip all the CRT stuff from your executable at the expense of not having the C runtime library linked. Not sure whether this is what you would like to have.</p>
5890
2014-07-18T08:32:42.497
<p>I compiled the following C++ code with <a href="http://en.wikipedia.org/wiki/MinGW" rel="nofollow">MinGW</a> and opened it in OllyDbg 2.01. And the program stops at the following lines:</p> <pre><code>CPU Disasm Address Hex dump Command Comments 00401570 /$ 83EC 1C SUB ESP,1C 00401573 |. C70424 010000 MOV DWORD PTR SS:[LOCAL.6],1 0040157A |. FF15 68814000 CALL DWORD PTR DS:[&lt;&amp;msvcrt.__set_app_ty 00401580 \. E8 FBFBFFFF CALL 00401180 Names in Project1, item 20 Address = 00401570 Section = .text Type = Export Ordinal = Name = &lt;ModuleEntryPoint&gt; Comments = </code></pre> <p>However, this is not what I want. I prefer when OllyDbg stop at the following lines:</p> <pre><code>CPU Disasm Address Hex dump Command Comments 004016B0 /$ 55 PUSH EBP ; Project1.004016B0(guessed void) 004016B1 |. 89E5 MOV EBP,ESP 004016B3 |. 83E4 F0 AND ESP,FFFFFFF0 ; DQWORD (16.-byte) stack alignment 004016B6 |. 83EC 10 SUB ESP,10 004016B9 |. E8 A2050000 CALL 00401C60 004016BE |. C70424 645040 MOV DWORD PTR SS:[LOCAL.4],OFFSET 004050 ; /format =&gt; "Hello World!" 004016C5 |. E8 9E1F0000 CALL &lt;JMP.&amp;msvcrt.printf&gt; ; \MSVCRT.printf 004016CA |. B8 00000000 MOV EAX,0 004016CF |. C9 LEAVE 004016D0 \. C3 RETN </code></pre> <p>Is that a bug? Why did MinGW set <code>SUB ESP, 1C</code> as the entrypoint? Can I set Ollydbg to start at the correct entrypoint?</p>
Why did the program entry point become 'sub esp, 1C'?
|ollydbg|debugging|c++|
<p>Going over </p> <ul> <li><a href="https://github.com/kbandla/ImmunityDebugger/blob/master/docs/dc-15-gomez.pdf" rel="nofollow noreferrer">ImmunityDbg presentation</a> - page 26, </li> <li><a href="https://github.com/kbandla/ImmunityDebugger/tree/master/1.73" rel="nofollow noreferrer">v1.73 dir</a> - dir structure</li> <li><a href="https://github.com/kbandla/ImmunityDebugger/blob/master/1.73/Documentation/IMMLIB.HLP" rel="nofollow noreferrer">ImmDbg help file</a> - "PyHooks ... they look exactly as a python plugin, only that they are placed inside PyHooks directory."</li> </ul> <p>I'm making and educated guess that <code>PyPlugins</code> is probably a leftover from previous versions of the debugger and at some point it became known as <code>PyScripts</code>.</p> <p>So, the actual examples and guidance could be found <a href="https://github.com/kbandla/ImmunityDebugger/tree/master/1.73/PyScripts" rel="nofollow noreferrer">here</a> </p>
5896
2014-07-19T08:10:42.750
<p><a href="http://www.immunityinc.com/products-immdbg.shtml" rel="noreferrer">Immunity Debugger</a> offers a feature called <strong>PyPlugin</strong>. However there is not enough documentation on it. The help for immdbg says this :</p> <blockquote> <p>PyPlugins are python scripts located at PyPlugins\ directory, PyPlugins are called when F4 or the PyPlugin icon located at the main toolbar are pressed. Both (F4 or the PyPlugin icon) will popup a file browse dialog, where the starting folder is the PyPlugin Directory. When a pyplugin is executed, its main() gets called. Please note a pyplugin can not receive any arguments and will not return any value other than inscreen errors.</p> </blockquote> <p>In reality when the <kbd>F4</kbd> key is pressed, nothing special happens. <kbd>F4</kbd> is actually the shortcut to <em>Run to selection</em>. Further there is no <em>PyPlugin</em> icon located at the main toolbar. The <em>PyPlugins</em> directory under Immunity Debugger directory is also empty, so no examples to look.</p> <p>My question is what is a <em>PyPlugin</em> ? Are there any ready made <em>PyPlugins</em> to refer as an example ?</p> <p><sub><strong>Note</strong> : I am only talking about <strong>PyPlugins</strong>, not <strong>PyCommands</strong></sub></p>
Immunity Debugger PyPlugin
|python|immunity-debugger|
<p>Since a dylib file is just going to be a Mach-O file, you're going to need to understand the header format, which is laid out pretty well in the code itself. You can take a look at the Mach-O parsing functions on Apple's site</p> <p><a href="http://www.opensource.apple.com/source/xar/xar-45/xar/lib/macho.c" rel="nofollow">http://www.opensource.apple.com/source/xar/xar-45/xar/lib/macho.c</a></p> <p>What you're seeing is that FAT Header part of the Mach-O file, which is telling you where to find the rest of the of the Mach-O file. This is used to have one file, with two separate architectures inside of it. The FAT header describes where the to find the rest of the data needed by the system running it.</p> <p>While doing some reversing and forensics work, I created a 010Editor template for parsing through Mach-O files - it might be useful in conjunction with the source from Apple for understanding what is coming after the 0xCAFEBABE and loading you're actual dylib files;</p> <p><a href="https://github.com/strazzere/010Editor-stuff/blob/master/Templates/MachOTemplate.bt" rel="nofollow">https://github.com/strazzere/010Editor-stuff/blob/master/Templates/MachOTemplate.bt</a></p>
5898
2014-07-19T21:18:41.363
<p>My end goal here is to find the Mach-O header in a dylib file.</p> <p>Here's what I've come up with so far:</p> <p>All my dylib files have the following first four bytes: 0xcafebabe. Then after 4096 bytes the actual Mach-O header starts, followed by the usual commands and so on.</p> <p>But 0xcafebabe is also used to identify Java class files. So how do I distinguish between both of those based on the actual content? What are the fields after 0xcafebabe in a dylib file?</p>
How are dylib files laid out
|disassembly|binary|
<p>Maybe the decompiler failed to recognize a register argument to <code>new()</code>. <code>new(n)</code> usually takes a <code>nr</code> of bytes, and allocates memory.</p> <p><code>sub_100033ae</code> just forwards the call to new.</p>
5899
2014-07-19T21:23:59.383
<p>I'm using <code>IDA Pro</code> with the Hexrays decompiler.</p> <p>There is a function like this:</p> <p><img src="https://i.stack.imgur.com/4QJT6.png" alt="Function 1"></p> <p>That function assigns the result of <code>sub_100033AE</code> to <code>dword_10005368</code>. So to know what the <code>DWORD</code> is, I checked what does that <code>sub_100033AE</code> do, but surprise...</p> <p><img src="https://i.stack.imgur.com/JfU1J.png" alt="Function 2"></p> <p>Its assembly is:</p> <p><img src="https://i.stack.imgur.com/qn1RQ.png" alt="enter image description here"></p> <p>What I am wondering is: how is it just returning a call to <code>new()</code>? What is its purpose? What does it return?</p>
Forwarded call to "operator new()" in IDA Pro
|ida|
<p>You shoudl use an SPI flash parallel port programmer. It is a simple and very accurate programmer using a single 74ls244 ic. </p> <p>You can get it at: <a href="http://www.spiflash.org/" rel="nofollow">http://www.spiflash.org/</a></p>
5901
2014-07-20T11:55:50.833
<p>Can someone recommend a handy inexpensive USB programmer for <a href="http://www.spansion.com/Support/Datasheets/S25FL064A_00.pdf" rel="nofollow">SPANSION S25FL064P</a> flash memory?</p>
USB programmer for SPANSION S25FL064P flash memory
|hardware|linux|firmware|memory|
<p>I would define a vtable struct which has the correct function pointers in it. I assume this is an <code>IDirectDrawSurfaceX</code>? The variable named <code>v17-&gt;lpVtbl</code> needs to have a type of <code>IDirectDrawSurfaceX *</code>. Create this structure of function pointers according to the interface definition on MSDN or load it from a standard structures if IDA has imported the DirectX C interface definitions. Set the type of the <code>v17-&gt;lpVtbl</code> by pressing <kbd>y</kbd> on the definition of lpVtbl in whatever structure type <code>v17</code> is. Then you may need to force the type of the function pointer call to the type of the interface member used in the vtable. You do this by right clicking the call site and choosing <code>Force call type</code>.</p>
5904
2014-07-20T14:40:57.810
<p>In a disassembly with a call to a <code>DirectDraw-&gt;BltFast</code> function, I encountered the following:</p> <pre><code>(*(void (__stdcall **)(LPDIRECTDRAWSURFACE7, _DWORD, _DWORD, _DWORD, _DWORD, signed int, int, int, int, int)) ((void (__stdcall **)(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD))v17-&gt;lpVtbl + 7))( v17, 0, 0, *(&amp;g_COREvidSurf + 25), 0, 16, v75, v77, v79, v81); </code></pre> <p>The cast has too many arguments. How does one edit the call's cast to fix the disassembly ?</p> <p>EDIT: After applying a struct to the code:</p> <pre><code>.text:00540825 030 cmp [esp+30h+arg_8], ecx .text:00540829 030 mov edx, g_COREvidSurf+64h .text:0054082F 030 mov eax, g_CoreVidsurf_6 .text:00540834 030 push 10h .text:00540836 034 push 0 .text:00540838 038 push edx .text:00540839 03C push 0 .text:0054083B 040 push 0 .text:00540844 044 mov ecx, [eax] .text:00540846 044 push eax .text:00540847 048 mov eax,[ecx+IDirectDrawSurface7Vtbl.BltFast] .text:0054084A 048 call eax </code></pre> <p>and the decompilation:</p> <pre><code>v17.lpVtbl = (struct IDirectDrawSurface7::IDirectDrawSurface7Vtbl *)g_surface2; (*(void (__stdcall **)(struct IDirectDrawSurface7::IDirectDrawSurface7Vtbl *, _DWORD, _DWORD, _DWORD, _DWORD, signed int, int, int, int, int))(*(_DWORD *)v17.lpVtbl + offsetof(IDirectDrawSurface7Vtbl, BltFast)))( v17.lpVtbl, 0, 0, *(&amp;g_COREvidSurf + 25), 0, 16, v75, v77, v79, v81); </code></pre> <p>The struct used was selected from the standard struct selection in IDA, and if i press 'Y' on the declaration of BltFast in the struct declaration, the call is declared like this:</p> <pre><code>HRESULT (__stdcall *BltFast)(IDirectDrawSurface7 *This, DWORD, DWORD, LPDIRECTDRAWSURFACE7, LPRECT, DWORD) </code></pre> <p>which is correct, but as seen above, IDA is still showing too many args.</p>
How to fix the type of a function pointer call in the Hex-Rays decompiler?
|ida|disassembly|