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
<blockquote> <p>how does the Unix loader know what is the module, shared object where to search for this symbol</p> </blockquote> <p>Short answer: it does not. It just searches the whole list of loaded modules until the symbol is found (or not). A small degree of control over more exact symbol matching can be achieved via versioned symbols but otherwise it's pretty much a free-for-all.</p> <p>By design, the ELF symbol space is <strong>global</strong> (or flat) so any symbol can be <em>preempted</em> by another module. This is used for example when <a href="http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/" rel="nofollow noreferrer">hooking symbols via LD_PRELOAD_LIBRARY environment variable</a>.</p>
22640
2019-11-29T12:21:21.150
<p>(in Windows) PE file format contains Import table with <code>Module\Dll Name</code> which tells PE loader where to search for symbol e.g. <code>KERNEL32.dll -&gt; CreateFileW</code></p> <p>In the ELF file format there is <code>Symbol table</code> with <code>info</code> field which tells if the symbol is <code>Global\Local\Weak\etc.</code></p> <p>My question is how does the Unix loader know what is the module, shared object where to search for this symbol e.g. <code>???? -&gt; snprintf</code></p> <p>I noticed objdump can dump this info <code>objdump -T /bin/ls</code>. <a href="https://i.stack.imgur.com/laK3P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/laK3P.png" alt="enter image description here"></a> <code>GLIBC_2.2.5 snprintf</code></p> <p>Could someone with more knowledge on ELF file format shed some light on Unix dynamic-linking?</p>
ELF file format find shared object for symbol
|elf|dynamic-linking|
<p>You can use Ida's <a href="https://hex-rays.com/products/ida/support/tutorials/debugging_appcall.pdf" rel="nofollow noreferrer">Appcall</a> functionality:</p> <blockquote> <p>Appcall is a mechanism to call functions inside the debugged program from the debugger or your script as if it were a built-in function. Such a mechanism can be used for debugging, fuzzing and testing applications. Appcall mechanism highly depends on the type information of the function to be called. For that reason it is necessary to have a correct function prototype before doing an Appcall, otherwise different or incorrect results may be returned.</p> </blockquote> <p>If it's an elf and you don't have Ida, <a href="https://lief.quarkslab.com" rel="nofollow noreferrer">LIEF</a> is a good option. You can see a tutorial to export an internal function and call it <a href="https://lief.quarkslab.com/doc/latest/tutorials/08_elf_bin2lib.html" rel="nofollow noreferrer">here</a></p>
22647
2019-11-30T17:59:51.780
<p>Is it possible to call a function of a binary and obtain its result (without calling other functions), to isolate; are there any tools to do this?</p>
Isolate the call to a function
|x86-64|assembly|
<p>In IDA, you can setup a breakpoint and use its <code>condition</code> property in Edit Breakpoint. This way you can modify registers, memory, or even perform very complex actions using IDC scripting, for example:</p> <pre><code>patch_dbg_byte(rcx+2,0),0 </code></pre> <p>Above will clear byte at address <code>rcx+2</code> when breakpoint is hit.</p>
22668
2019-12-03T15:24:14.510
<p>I'm debugging some code and I know that there's a structure in memory, I have a definition of the structure, I apply it on memory, then I look at the structure field values, and I see that one of the fields of the structure contains the wrong value. Is there any way to change the structure field value?</p> <p>Currently I have to look for the offset of the field in structure definitions, then undefine the structure in memory, then go to the proper offset, change the value and reapply the structure again.</p>
Is there a way to edit structure field value in memory during debug
|ida|
<p>The special "accent" letters are just a distraction. You can use a text-editor to replace them with "standard" letters and the code would still work.</p> <p>Let's add a newline after each semicolon:</p> <pre><code>É=-~-~[],ó=-~É,Ë=É&lt;&lt;É,þ=Ë+~[]; Ì=(ó-ó)[Û=(''+{})[É+ó]+(''+{})[ó-É]+([].ó+'')[ó-É]+(!!''+'')[ó]+({}+'')[ó+ó]+(!''+'')[ó-É]+(!''+'')[É]+(''+{})[É+ó]+({}+'')[ó+ó]+(''+{})[ó-É]+(!''+'')[ó-É]][Û]; Ì(Ì((!''+'')[ó-É]+(!''+'')[ó]+(!''+'')[ó-ó]+(!''+'')[É]+((!''+''))[ó-É]+([].$+'')[ó-É]+'\''+''+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(þ)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(ó-ó)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(É+ó)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(ó-ó)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+ó)+(ó-ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(ó-ó)+(É+ó)+'\\'+(ó-É)+(É+ó)+(ó+ó)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(þ)+(É)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(É+ó)+(É+ó)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(É+É)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(ó+ó)+(ó-ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(ó+ó)+(ó)+'\\'+(ó-É)+(ó+ó)+(ó)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(þ)+(ó)+'\\'+(ó-É)+(É+ó)+(ó-É)+'\\'+(ó-É)+(É+É)+(ó+ó)+'\\'+(É+ó)+(ó-ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(þ)+(É+ó)+'\\'+(þ)+(É+ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó+ó)+(ó-É)+'\\'+(ó+ó)+(É)+'\\'+(ó+ó)+(ó)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(ó-É)+(þ)+(ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+ó)+(ó-ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(É+É)+(É)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(ó+ó)+(ó+ó)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(þ)+(ó)+'\\'+(ó-É)+(þ)+(É+ó)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(ó+ó)+(ó)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(þ)+(ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+ó)+(ó-ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(É+É)+(ó+ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(É+ó)+(ó-É)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(É+ó)+(ó+ó)+'\\'+(É+ó)+(ó+ó)+'\\'+(É+ó)+(ó+ó)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(þ)+(ó)+'\\'+(ó-É)+(þ)+(É+ó)+'\'')())() </code></pre> <p>We can see that the first and second lines assign values to several variables (<code>É</code>, <code>ó</code>, <code>Ë</code>, <code>þ</code>, <code>Ì</code>). Then, the third line calls <code>Ì</code> (since it ends with '<code>()</code>').</p> <p>In order to de-obfuscate the code, you can paste it in the browser console and replace the last two characters ('<code>()</code>') with <code>.toString()</code> - printing the function instead of calling it.</p> <p>The result would be:</p> <pre><code>"function anonymous( ) { a=prompt('Entrez le mot de passe');if(a=='toto123lol'){alert('bravo');}else{alert('fail...');} }" </code></pre>
22679
2019-12-06T17:52:04.303
<p>I am trying to deobfuscate this javascript code, but I don't know how it was created. Can you please tell me what the mechanism or the function is that generate such characters in javascript?</p> <pre><code>É=-~-~[],ó=-~É,Ë=É&lt;&lt;É,þ=Ë+~[];Ì=(ó-ó)[Û=(''+{})[É+ó]+(''+{})[ó-É]+([].ó+'')[ó-É]+(!!''+'')[ó]+({}+'')[ó+ó]+(!''+'')[ó-É]+(!''+'')[É]+(''+{})[É+ó]+({}+'')[ó+ó]+(''+{})[ó-É]+(!''+'')[ó-É]][Û];Ì(Ì((!''+'')[ó-É]+(!''+'')[ó]+(!''+'')[ó-ó]+(!''+'')[É]+((!''+''))[ó-É]+([].$+'')[ó-É]+'\''+''+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(þ)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(ó-ó)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(É+ó)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(ó-ó)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+ó)+(ó-ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(ó-ó)+(É+ó)+'\\'+(ó-É)+(É+ó)+(ó+ó)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(þ)+(É)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(É+ó)+(É+ó)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(É+É)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(É+É)+(ó-ó)+'\\'+(ó-É)+(ó+ó)+(ó-ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(ó+ó)+(ó)+'\\'+(ó-É)+(ó+ó)+(ó)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(þ)+(ó)+'\\'+(ó-É)+(É+ó)+(ó-É)+'\\'+(ó-É)+(É+É)+(ó+ó)+'\\'+(É+ó)+(ó-ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(þ)+(É+ó)+'\\'+(þ)+(É+ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó+ó)+(ó-É)+'\\'+(ó+ó)+(É)+'\\'+(ó+ó)+(ó)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(ó-É)+(þ)+(ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+ó)+(ó-ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(É+É)+(É)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(ó+ó)+(ó+ó)+'\\'+(ó-É)+(É+ó)+(þ)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(þ)+(ó)+'\\'+(ó-É)+(þ)+(É+ó)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(ó+ó)+(ó)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(þ)+(ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(ó-É)+(É+É)+(É+ó)+'\\'+(ó-É)+(ó+ó)+(É)+'\\'+(ó-É)+(ó+ó)+(É+É)+'\\'+(É+ó)+(ó-ó)+'\\'+(É+É)+(þ)+'\\'+(ó-É)+(É+É)+(ó+ó)+'\\'+(ó-É)+(É+É)+(ó-É)+'\\'+(ó-É)+(É+ó)+(ó-É)+'\\'+(ó-É)+(É+ó)+(É+É)+'\\'+(É+ó)+(ó+ó)+'\\'+(É+ó)+(ó+ó)+'\\'+(É+ó)+(ó+ó)+'\\'+(É+É)+(þ)+'\\'+(É+ó)+(ó-É)+'\\'+(þ)+(ó)+'\\'+(ó-É)+(þ)+(É+ó)+'\'')())() </code></pre>
How can I deobfuscate this javascript code
|deobfuscation|javascript|
<p>It looks like that previous code had an optimization done, so that if the left-hand side value was evaluated as <code>false</code> the right one was not evaluated at all in the <code>&amp;&amp;</code> operation as it would never result in <code>true</code> anyway and <code>false</code> can be used directly.</p> <p>Currently there's no such code but you can clearly see the <code>and</code> being done, preceded by <code>ldloc.0</code>. There's a missing code from the beginning of this function but if local variable at index 0 is your <code>flag</code> you can remove those two instructions (so lines 81 and 82). From the code it looks like on the stack there should already by also a <code>1</code> so that the instruction that stores the value with <code>stfld</code> will work. If not you could add a <code>ldc.i4.1</code> instead of those two that you removed.</p>
22681
2019-12-07T01:52:19.650
<p>Background info - For the game 7 Days To Die, there is a C# wrapper that implements the Harmony API, which allows us to intercept the game's function calls, as well as changing the IL instructions themselves.</p> <p>I originally used the Transpiler functionality to remove a condition that's used in two checks. Which was easy enough, as I just needed to remove three instructions. Here's a screenshot showing them: </p> <p><img src="https://i.stack.imgur.com/r5Wmj.png" alt=""></p> <p>On the left is the old code, which was easy enough to modify. I just needed to remove the instructions at indexes <strong>79</strong>, <strong>80</strong>, and <strong>81</strong>. Which changes the C# code from:</p> <pre><code>this.cmds[1].enabled = (_world.IsEditor() &amp;&amp; flag); </code></pre> <p>To:</p> <pre><code>this.cmds[1].enabled = (flag); </code></pre> <p>Which worked perfectly. However, the DLL was changed in an update. The C# code is the exact same, but the IL instructions differ at this very last condition check. And I can't quite wrap my head around it.</p> <p>The original was easy enough. <code>IL 79</code> prepares something for the next function call, <code>IL 80</code> makes the call, and <code>IL 81</code> jumps past the next couple of instructions if it returns false. In ASM, the three instructions would basically be <code>pop</code> (call class' function via a pointer), <code>cmp</code> (check the boolean result), and <code>jz</code> (jump if false).</p> <p>But the updated IL instructions on the right don't make any sense to me. There's no branch, there's no jump. How do I work with that to remove the <code>_world.IsEditor()</code> condition?</p> <p>Edit: <a href="https://pastebin.com/XEncgdet" rel="nofollow noreferrer">Pastebin of the C# function</a></p>
C# - Identical block of code, but IL instructions changed after update. How do I modify the more convoluted update?
|c#|
<p>From <a href="https://github.com/Siguza/ios-resources/blob/master/bits/arm64.md" rel="nofollow noreferrer">https://github.com/Siguza/ios-resources/blob/master/bits/arm64.md</a></p> <blockquote> <p>x8 pointer to where to write the return value if >128 bits, otherwise scratch register</p> </blockquote> <p>So it seems x8 is used to pass an address at which the return value will land if it's too big, rather than the return value directly, hence indirect I suppose.</p> <p>I couldn't find official documentation as the ARM page was barely loading for me.</p>
22701
2019-12-09T13:29:12.580
<p>I have <code>usercall</code> with calling convention I do not fully understand, it returns <code>std::string</code> but IDA recognize it as <code>void</code>.</p> <p>I've noticed that every calle reads from <code>x8/w8</code> afterwards, from <a href="https://en.wikipedia.org/wiki/Calling_convention#ARM_(A64)" rel="nofollow noreferrer">wikipedia</a>;</p> <blockquote> <p>x8: used to hold indirect return value address</p> </blockquote> <p>Can someone explain "<em>indirect return value address</em>" ? </p> <p>From <a href="https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=vs-2019" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=vs-2019</a></p> <blockquote> <p>Return values </p> <p>Integral values are returned in x0.</p> <p>Floating-point values are returned in s0, d0, or v0, as appropriate.</p> <p>HFA and HVA values are returned in s0-s3, d0-d3, or v0-v3, as appropriate.</p> <p>Types returned by value are handled differently depending on whether they have certain properties. Types which have all of these properties,</p> <p>they're aggregate by the C++14 standard definition, that is, they have no user-provided constructors, no private or protected non-static data members, no base classes, and no virtual functions, and they have a trivial copy-assignment operator, and they have a trivial destructor, use the following return style:</p> <p>Types less than or equal to 8 bytes are returned in x0. Types less than or equal to 16 bytes are returned in x0 and x1, with x0 containing the lower-order 8 bytes. </p> <p><strong>For types greater than 16 bytes, the caller shall reserve a block of memory of sufficient size and alignment to hold the result. The address of the memory block shall be passed as an additional argument to the function in x8. The callee may modify the result memory block at any point during the execution of the subroutine. The callee isn't required to preserve the value stored in x8.</strong> </p> <p>All other types use this convention:</p> <p>The caller shall reserve a block of memory of sufficient size and alignment to hold the result. The address of the memory block shall be passed as an additional argument to the function in x0, or x1 if $this is passed in x0. The callee may modify the result memory block at any point during the execution of the subroutine. The callee returns the address of the memory block in x0.</p> </blockquote> <p>Update 2:</p> <p>From <a href="https://static.docs.arm.com/den0024/a/DEN0024A_v8_architecture_PG.pd" rel="nofollow noreferrer">ARM docs</a></p> <blockquote> <p>Registers with a special purpose </p> <p>• X8 is the indirect result register. This is used to pass the address location of an indirect result, for example, where a function returns a large structure. ...</p> <p>... the structure contains more than 16 bytes. According to the AAPCS for AArch64, the returned object is written to the memory pointed to by XR.</p> </blockquote>
indirect return value address
|ida|c++|calling-conventions|arm64|
<p>It seems CSB is <a href="https://electronics.stackexchange.com/questions/453360/why-ss-and-miso-of-sensor-is-permanently-high">Chip select</a>, and MISO (Master in/Slave out) is a typical name for an SPI pin. </p>
22709
2019-12-10T06:17:06.023
<p>i have a vtech baby monitor and since i want to be aware of it while i'm playing in VR (PC, HTC vaive/Valve index) i still want to see if the baby starts crying.</p> <p>on this monitor there is external access to a 6 pin connector. opening the unit i see the pins are labeled: SF_CSB, SF_MISO, VDD3, TX, RX, GND.</p> <p>The VDD,TX,RX,GND i think its a UART port, i need help identifying the other 2 pins. i found them on some LG TV's manuals but without explanation.</p> <p>anybody is familiure with this port?</p>
id the HW port and protocol
|hardware|serial-communication|
<p>You can find some plugins that does the functions renaming for go language (and others as well). For example <a href="https://github.com/ghidraninja/ghidra_scripts" rel="nofollow noreferrer">this one</a> could be used and after renaming bunch of methods can be seen: <a href="https://i.stack.imgur.com/Q9pF0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q9pF0.png" alt="enter image description here"></a></p>
22713
2019-12-10T15:53:13.783
<p>I'm reversing a binary that was apart of a CTF I was involved in about a month ago. It was too large of a binary to do during the challenge so I am doing it now.</p> <p>I am having trouble finding the <em>main function</em> because the entry function is not the same as if this was written in C and compiled with GCC. I was wondering how I could go about finding the main function and if there were any resources that could assist me in my endeavors. </p>
Finding "func main" in a stripped binary written in GO
|binary-analysis|binary|ghidra|x86-64|
<p>You can go to function A and press <code>y</code> on the call to B, and edit to <code>int B(int a, int b)</code></p>
22719
2019-12-11T14:20:43.027
<p>I am on the last version of IDA.</p> <p>There is a function B, that its signature is <code>B(int a,int b)</code>.</p> <p>There is a function A that calls it. But in function A, the call appears like <code>B(12)</code> for example.</p> <p>How do I make it synchronized / decompile just function A again? </p> <p>Thanks.</p>
IDA decompiled function signature mismatch
|ida|
<p>This is probably Blowfish.</p> <p>Googling the constants "0x448 0xC48 crypto" lead to this post:</p> <p><a href="https://reverseengineering.stackexchange.com/questions/19042/trying-to-identify-block-of-code-which-generates-256-bit-key">Trying to identify block of code which generates 256 bit key</a></p> <p>where someone in the comments wrote</p> <pre><code>googling the constants 0xc48, 0x848 and 0x448 is a good idea. rohitab.com/discuss/topic/36066-blowfish relates this to blowfish somehow </code></pre> <p>and that link has code that looks very similar:</p> <p><a href="http://www.rohitab.com/discuss/topic/36066-blowfish/" rel="nofollow noreferrer">http://www.rohitab.com/discuss/topic/36066-blowfish/</a></p> <p>(search for <code>C48</code> there).</p> <p>The only oddity is that the author of that other post says he is sure it is AES and he said he could decrypt some data using AES. I don't know how to consolidate both ideas, but it's probably either and given the similar disassemblies I'd say Blowfish.</p> <p>Doesn't look like AES to me either but I had some AES-related crypto before that looked a bit like this - Blowfish is way more convincing.</p>
22736
2019-12-14T09:18:54.720
<p>I've used x64dbg to work out decryption in a particular program. I've found where it changes the encrypted material into readable text but can't work out the best way to use this information to convert multiple files. </p> <p>Is it a standardized encryption method? (eg. blowfish/aes) <a href="https://i.stack.imgur.com/1NHhk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1NHhk.png" alt="Assembler"></a></p> <p>It basically copies the file to memory then cycles through this (and one other cycle above it).</p> <p>Thanks!</p> <p>Addit 15/12/2019: <strong>OUTER FUNCTION</strong> <a href="https://i.stack.imgur.com/DA8WH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DA8WH.png" alt="enter image description here"></a></p> <p>Ouput of signsrch:</p> <pre><code> offset num description [bits.endian.size] -------------------------------------------- 0002b542 2249 TEA1_DS [32.le.4] 00059090 2065 Haval init [32.le.32&amp;] 00059090 919 Blowfish bfp table [32.le.72] 000590b0 1054 Haval hash pass2 [32.le.128&amp;] 000590e0 921 Blowfish ks0 table [32.le.1024] 000590e0 2335 Blowfish_s_init [32.le.4096] 00059138 2067 Haval mc3 [32.le.128] 00059198 2219 HAVAL2_DS [32.le.32] 000591b8 2069 Haval mc4 [32.le.128] 00059218 2217 HAVAL1_DS [32.le.32] 00059238 2071 Haval mc5 [32.le.128] 000594e0 923 Blowfish ks1 table [32.le.1024] 000598e0 925 Blowfish ks2 table [32.le.1024] 00059ce0 927 Blowfish ks3 table [32.le.1024] 007b1a86 2545 anti-debug: IsDebuggerPresent [..17] 007b7e07 1038 padding used in hashing algorithms (0x80 0 ... 0) [..64] </code></pre> <p>It must be blowfish. Now to find the key!!!</p>
Help with reversing decryption in assembly
|decryption|
<p>The output of rabin2 is definitely a bit cryptic, here is some of the information I found for the components that you asked about.</p> <h3>crypto</h3> <p>Boolean flag that indicates if a binary is encrypted/packed</p> <h3>relocs</h3> <p>Indicates that the binary performs run time relocation</p> <h3>va</h3> <p>Indicates that virtual addressing is in use, it will be false if rabin2 is run with the <code>-p</code> flag</p> <h3>linenum</h3> <p>The linenum information that is present in the DWARF debug section of the ELF binary</p> <h3>pcalign</h3> <p>Related to data structure alignment, could refer to the <code>p_align</code> member in the ELF program header. <code>p_align</code> gives the value to which segments are aligned in memory and in the file. The values 0 and 1 mean no alignment is required</p> <p>Some links that could provide more context</p> <ul> <li><a href="https://dzhy.dev/2020/02/28/Understanding-rabin2-output/" rel="nofollow noreferrer">Rabin2 output</a></li> <li><a href="https://erani.kapsi.fi/posts/2018-03-11-reverse-engineering-basics-with-radare-binary-internals/" rel="nofollow noreferrer">Reversing basics with radare2</a></li> <li><a href="https://blog.tartanllama.xyz/writing-a-linux-debugger-elf-dwarf/" rel="nofollow noreferrer">Building a Linux Debugger</a></li> <li><a href="https://en.wikipedia.org/wiki/Data_structure_alignment" rel="nofollow noreferrer">Data structure alignment</a></li> </ul>
22745
2019-12-15T09:32:42.670
<p>I am wondering what the <strong>crypto</strong>, <strong>linenum</strong>, <strong>pcalign</strong>, <strong>relocs</strong> and <strong>va</strong> values mean in the output of rabin2.</p> <p>I took a look in the source code of radare2 and it seems for ELF <strong>va</strong> is always true, I assume it means virtual addressing?</p> <p><a href="https://github.com/radareorg/radare2/blob/1d3698bc96a09e45c4fff4c090278623f146929c/libr/bin/format/elf/elf.c#L2132-L2134" rel="nofollow noreferrer">https://github.com/radareorg/radare2/blob/1d3698bc96a09e45c4fff4c090278623f146929c/libr/bin/format/elf/elf.c#L2132-L2134</a></p> <pre><code>int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) { return true; } </code></pre> <p>I would assume <strong>relocs</strong> refer to the presence of the relocation table however from my testing that does not seem to be the case.</p> <p>For <strong>linenum</strong> I think it refers information relating to the line numbers in the source code? But this still seem to appear true when there is no DWARF information on the ELF binary.</p> <p>As for the other 2 I have no idea what they are referring to.</p> <pre><code>arch x86 baddr 0x0 binsz 6618 bintype elf bits 64 canary true sanitiz false class ELF64 crypto false endian little havecode true intrp /lib64/ld-linux-x86-64.so.2 laddr 0x0 lang c linenum true lsyms true machine AMD x86-64 architecture maxopsz 16 minopsz 1 nx true os linux pcalign 0 pic true relocs true relro full rpath NONE static false stripped false subsys linux va true </code></pre>
Understanding output of rabin2
|radare2|
<p>It seems your binaries are little-endian, so you neeed qemu-mips<strong>el</strong>.</p>
22765
2019-12-17T06:38:50.020
<p>I'm trying to emulate a MIPS binary on my Ubuntu 16.04 x86 system, but I'm not able to. I <code>chroot</code> into the <code>squashfs-root</code> filesystem that I got from <code>binwalk</code>ing the firmware image.</p> <pre><code>kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ ls -l total 3092 drwxr-xr-x 2 kan3k1 kan3k1 4096 Mar 18 2018 bin drwxr-xr-x 5 kan3k1 kan3k1 4096 Mar 18 2018 dev drwxr-xr-x 5 kan3k1 kan3k1 4096 Mar 18 2018 etc drwxr-xr-x 3 kan3k1 kan3k1 4096 Mar 18 2018 lib lrwxrwxrwx 1 kan3k1 kan3k1 11 Mar 18 2018 linuxrc -&gt; bin/busybox drwxr-xr-x 2 kan3k1 kan3k1 4096 Mar 18 2018 mnt drwxr-xr-x 2 kan3k1 kan3k1 4096 Mar 18 2018 proc -rwxr-xr-x 1 kan3k1 kan3k1 3120160 Dec 17 01:07 qemu-mips-static drwxr-xr-x 2 kan3k1 kan3k1 4096 Mar 18 2018 sbin drwxr-xr-x 2 kan3k1 kan3k1 4096 Mar 18 2018 sys drwxr-xr-x 4 kan3k1 kan3k1 4096 Mar 18 2018 usr drwxr-xr-x 2 kan3k1 kan3k1 4096 Mar 18 2018 var drwxr-xr-x 9 kan3k1 kan3k1 4096 Mar 18 2018 web kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ sudo chroot . ./qemu-mips-static ./bin/ls ./bin/ls: Invalid ELF image for this architecture kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ sudo chroot . ./qemu-mips-static ./bin/busybox ./bin/busybox: Invalid ELF image for this architecture kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ file bin/ls bin/ls: symbolic link to busybox kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ file bin/busybox bin/busybox: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), dynamically linked, interpreter /lib/ld-uClibc.so.0, stripped kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ rabin2 -I ./bin/ls arch mips baddr 0x400000 binsz 260852 bintype elf bits 32 canary false class ELF32 crypto false endian little havecode true intrp /lib/ld-uClibc.so.0 laddr 0x0 lang c linenum false lsyms false machine MIPS R3000 maxopsz 16 minopsz 1 nx false os linux pcalign 0 pic false relocs false relro no rpath NONE sanitiz false static false stripped true subsys linux va true kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ rabin2 -I ./bin/busybox arch mips baddr 0x400000 binsz 260852 bintype elf bits 32 canary false class ELF32 crypto false endian little havecode true intrp /lib/ld-uClibc.so.0 laddr 0x0 lang c linenum false lsyms false machine MIPS R3000 maxopsz 16 minopsz 1 nx false os linux pcalign 0 pic false relocs false relro no rpath NONE sanitiz false static false stripped true subsys linux va true </code></pre> <p>My system info:</p> <pre><code>kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ uname -a Linux kaido 4.15.0-29-generic #31~16.04.1-Ubuntu SMP Wed Jul 18 10:19:08 UTC 2018 i686 i686 i686 GNU/Linux </code></pre> <p>Any idea on how to resolve this? All the resources that I was able to find online have something to do with <code>.so</code> files causing the error.</p>
`qemu-mips-static` chroot causing `Invalid ELF image` error
|firmware|linux|mips|qemu|firmware-analysis|
<p>This happens because <code>__GETDS</code> is placed just after the entrypoint code and is initially detected by IDA as part of the <code>start</code> function:</p> <pre><code>cseg01:0001AAD1 push eax cseg01:0001AAD2 mov eax, 0 cseg01:0001AAD7 mov edx, 0Fh cseg01:0001AADC call __FiniRtns cseg01:0001AAE1 pop eax cseg01:0001AAE2 mov ah, 4Ch ; 'L' cseg01:0001AAE4 int 21h ; DOS - 2+ - QUIT WITH EXIT CODE (EXIT) cseg01:0001AAE4 ; AL = exit code cseg01:0001AAE6 mov eax, eax cseg01:0001AAE8 cseg01:0001AAE8 __GETDS: ; CODE XREF: __int23_handler+A↓p cseg01:0001AAE8 ; __int_ctrl_break_handler+A↓p ... cseg01:0001AAE8 __GETDSStart_: cseg01:0001AAE8 mov ds, cs:word_1AAF1 cseg01:0001AAF0 retn cseg01:0001AAF0 start endp </code></pre> <p>Since the call is to a middle of an existing function, IDA considers it to be non-returning and stops the code flow. The solution is to break <code>start</code> after the <code>int 21h</code> call (Set function end, or 'E' key) and create a proper function for <code>__GETDS</code> itself. Then you will need to reanalyze all call sites (and maybe recreate the functions) so that code flow is properly updated. </p>
22767
2019-12-17T13:29:14.393
<p>when trying to decompile some interrupt service routines done with Watcom, the __GETDS call at the beginning of the functions will break the decompiler output completely. Here's the disassembly: <a href="https://i.stack.imgur.com/UuPFE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UuPFE.png" alt="Disassembly"></a></p> <p>And here the decompiler output: <a href="https://i.stack.imgur.com/oJDoP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oJDoP.png" alt="Decompiler"></a></p> <p>What could be the reason for this? Is there a way to fix this? The only thing that worked for me was creating a separate function for the code below __GETDS, but that's not really satisfying. Thanks in advance!</p>
IDA Pro: __GETDS breaks decompiler output
|ida|decompiler|
<p><code>mov al, 1</code>, the instruction you want to use becomes <code>b0 01</code> (<a href="https://defuse.ca/online-x86-assembler.htm" rel="nofollow noreferrer">you can check here</a>), assuming x86-32. That is, <strong>2 Bytes</strong>.</p> <p>The instruction you are patching (<code>mov byte ptr ds:[ecx+0x72], al</code>) is <code>88 41 72</code> and so takes up <strong>3 Bytes</strong>. See the problem already?</p> <p>That means you are only patching the first two bytes of the instruction and need to pad it with a single-byte NOP (no operation, i.e. <code>90</code>) in order for all subsequent instructions to be correct.</p> <p>Otherwise the processor will start decoding at <code>&lt;patched-instruction&gt;+2</code> and assume that it is correct. Which it probably isn't.</p> <p><s>Not sure what all those screenshots are supposed to be about. They seem to have no relation to the instructions you said you were patching ...</s></p> <hr> <p>Now that you have posted the screenshot of the patch site, we can even potentially tell you what the CPU was trying to execute.</p> <p>The patch site before your patch was directly at the return from a function:</p> <pre><code>88 41 72 mov BYTE PTR [ecx+0x72],al c2 04 00 ret 0x4 ; ------ end of function 90 nop 90 nop 90 nop 90 nop 90 nop 90 nop </code></pre> <p>After your patch it would have looked like this:</p> <pre><code>b0 01 mov al,0x1 72 c2 jb 0xffffffc6 04 00 add al,0x0 ; ------ end of function 90 nop 90 nop 90 nop 90 nop 90 nop 90 nop </code></pre> <p>Still 12 Bytes overall (6 inside the function you were patching), but a completely different meaning. We can guess that either the jump instruction was taken and led into a location which gave the access violation, or that the condition (of <code>jb</code>) didn't evaluate to true and the CPU executed the <code>add</code> followed by 6x <code>nop</code> and then ended up in a completely different function (at least this looks like a function prologue) but with the stack still in place from the call to the previous function and so on ...</p>
22778
2019-12-19T02:31:40.873
<p>I'm trying to bypass the license of a very old software that i was using many years ago, now, the company of that software is closed and i can't get a license so, with a little bit of knowledge in assembly i changed </p> <pre><code>mov byte ptr ds:[ecx+0x72], al </code></pre> <p>to </p> <pre><code>mov al,1 </code></pre> <p><a href="https://i.stack.imgur.com/vHdd0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vHdd0.png" alt="enter image description here"></a> then i got </p> <p><a href="https://i.stack.imgur.com/ob0gZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ob0gZ.png" alt="enter image description here"></a></p> <p>The software compare a hash with the hash of the key code you entered, if it's the same, it will work <a href="https://i.stack.imgur.com/e36Zl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e36Zl.png" alt="enter image description here"></a> a random license request code generated everytime you run the .exe</p> <p>using GenerateRandomNumber <a href="https://i.stack.imgur.com/KDHjV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KDHjV.png" alt="enter image description here"></a> and hashed by using HkdfHashAlgorithm <a href="https://i.stack.imgur.com/QBSUm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QBSUm.png" alt="enter image description here"></a> here's the .exe</p> <p><a href="https://www.mediafire.com/file/ujd576jm8eg7oay/SpoolManager.exe/file" rel="nofollow noreferrer">https://www.mediafire.com/file/ujd576jm8eg7oay/SpoolManager.exe/file</a></p> <p>I'm not sure if that illigal to post it here, but I have no other solution</p> <p>Appreciate any help</p>
bypass license of very old software, Access violation (C0000005) x32dbg
|assembly|debugging|x64dbg|
<p>It seems the picked prototype is incorrect. The original version of <code>swprintf</code> does not have the count parameter. From the VS 9.0 (2008) CRT sources:</p> <pre><code>#ifndef _COUNT_ int __cdecl _swprintf ( wchar_t *string, const wchar_t *format, ... ) #else /* _COUNT_ */ #ifndef _SWPRINTFS_ERROR_RETURN_FIX /* Here we implement _snwprintf without the return value bugfix */ int __cdecl _snwprintf ( wchar_t *string, size_t count, const wchar_t *format, ... ) #else /* _SWPRINTFS_ERROR_RETURN_FIX */ int __cdecl _swprintf_c ( wchar_t *string, size_t count, const wchar_t *format, ... ) #endif /* _SWPRINTFS_ERROR_RETURN_FIX */ </code></pre>
22780
2019-12-19T07:40:23.403
<p>I have following code disassembled by ghidra:</p> <pre><code>PUSH EBX PUSH dword ptr [EBP + param_1] wchar_t * _Format for swprintf PUSH u_%s\%s_0040eb88 size_t _Count for swprintf PUSH dword ptr [EBP + param_3] wchar_t * _String for swprintf CALL dword ptr [-&gt;MSVCRT.DLL::swprintf] </code></pre> <p>The 2nd parameter is unicode string %s\%s, but it should be size_t parameter, because <a href="http://www.cplusplus.com/reference/cwchar/swprintf/" rel="nofollow noreferrer">swprintf</a> function requires count parameter</p> <p>This is another code which uses the same function:</p> <pre><code>LEA EAX=&gt;local_4dc,[0xfffffb28 + EBP] PUSH EAX wchar_t * _Format for swprintf LEA EAX=&gt;windowsDir,[0xfffffd30 + EBP] PUSH _Count_0040f40c size_t _Count for swprintf PUSH EAX wchar_t * _String for swprintf CALL EDI=&gt;MSVCRT.DLL::swprintf </code></pre> <p>Again, <code>_Count_0040f40c</code> is unicode string %/Program Data detected as <code>_Count</code></p> <p>Ghidra has correct function signature:</p> <pre><code>int swprintf (wchar_t * _String, size_t _Count, wchar_t * _Format, ...) </code></pre> <p>Normal count parameter is always missing, what Ghidra detects doesn't refer to number type variable. It looks like if all functions were compiled without it. All those memory variables ghidra detects as count parameters are actually format parameters. If there was actual count parameter every time swprintf was called, everything would be looking good.</p>
Function's signature with unmatching parameters
|functions|ghidra|
<p><strong>Algorithm</strong>: ((Licence request code) + 0x26946948) ^ (your serial number of <code>C:</code> volume or <code>0xffffffff</code> if failed).</p> <ul> <li><p>This <a href="https://play.golang.org/p/Wi2maUZ7ti_N" rel="nofollow noreferrer">keygen</a> I'm written in golang.</p></li> <li><p>Or javascript keygen <code> function keygen(code, serial) { code = parseInt(/([0-9-]{12})/.exec(code)[0].replace(/-/g, '')) return ((code + 0x26946948) ^ parseInt(serial.replace(/-/g, ''), 16)) &gt;&gt;&gt; 0 } // example // '9950-7444-3132-b9' is Licence request code // 'A639-6EDE' is Volume Serial Number of C: keygen('9950-7444-3132-b9', 'A639-6EDE') </code></p></li> </ul> <p><a href="https://i.stack.imgur.com/KaYOm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KaYOm.png" alt="serial"></a></p> <ul> <li>Or modify assembly at <strong>file.exe+178A</strong> <code>je file.exe+17B4</code> -> <code>jne file.exe+17B4</code> to bypass.</li> </ul>
22784
2019-12-19T17:13:32.373
<p>I'm trying to bypass (crack) a very old software that require license in order to unlock all the features</p> <p>i was digging in the lines with a little bit of knowledge in assembly and i found the line where it compare the hash of the request code with the hash of the license i entered</p> <p>this is the line ( not %100 sure ) <a href="https://i.stack.imgur.com/At4Dm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/At4Dm.png" alt="enter image description here"></a></p> <p>arrow1 where the random request code generated and the entered license saved to a param (not sure)</p> <p>arrow2 where the compare happen ( same not sure)</p> <p>The software compare a hash with the hash of the key code you entered, if it's the same, it will work</p> <p>a random license request code generated everytime you run the .exe</p> <p>using GenerateRandomNumber</p> <p><a href="https://i.stack.imgur.com/Juvh2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Juvh2.png" alt="enter image description here"></a></p> <p>and hashed by using HkdfHashAlgorithm</p> <p><a href="https://i.stack.imgur.com/U78SZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U78SZ.png" alt="enter image description here"></a></p> <p>my question is</p> <p>when i change <code>je 0x7C1AEF1F</code> to <code>jne 0x7C1AEF1F</code></p> <p><a href="https://i.stack.imgur.com/gIYl4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gIYl4.png" alt="enter image description here"></a></p> <p>the software stopped working and when i execute it i got the command prompt for 1second and disappear</p> <p><a href="https://i.stack.imgur.com/cEoRd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cEoRd.png" alt="enter image description here"></a></p> <p>so what i need to change in order to compare the hash of the request code with the same hash or to say if not equal so activated...</p> <p>Appreciate any help</p>
change compare function in assembly and .exe stopped working x64dbg
|assembly|debugging|x64dbg|
<p>try:</p> <p><code>printf '\x31\x09\x32' | xargs python script.py</code></p>
22793
2019-12-20T20:48:14.310
<p>I am working on a CTF where I need to pass an address as input to a program. This address contains the value 0x09 (the tab character). This is causing me problems, because it seems that bash is interpreting the tab before it is input to the actual program.</p> <p>Say I have a simple bash script:</p> <pre><code>#!/usr/bin/env bash echo $1 </code></pre> <p>I would then like to pass e.g. "1"+"\x09"+"2" and have the output from the program be: "1\x092".</p> <p>However the tab character moves the "2" to the second argument and it is then not echoed.</p> <p>Currently if I do</p> <pre><code>./script.sh $(python -c 'print "1"+"\x09"+"2"') </code></pre> <p>It just echos "1". Is there a way to keep the three characters tied together?</p> <p>Thanks in advance</p>
How to input ascii control character into program?
|linux|python|
<p>You can see the main module by going to "View -> Executable Modules" and selecting it instead of "ntdll".</p>
22796
2019-12-21T00:37:39.240
<p>I'm new to reverse enginnering and currently following Lena's tutorials. I wanted to put my new skills to use and wanted to reverse a simple game: <a href="https://github.com/Zolomon/labyrinth" rel="nofollow noreferrer">https://github.com/Zolomon/labyrinth</a>. </p> <p>I think I'm stuck somewhere in ntdll. How do I get out of that? It's after the game as been instantiated then everything stops working.</p> <p>I was hoping I would be stuck in the game loop and from there I was hoping to capture in-game movements. </p> <p>Below is a picture where I've put breakpoints right before the game window is created. <a href="https://i.stack.imgur.com/TCeMO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TCeMO.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/2fmAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2fmAI.png" alt="enter image description here"></a></p>
Stuck at ntdll when trying to enter a game loop
|debugging|
<p>Although this question is a bit broad, I feel that I can provide an acceptable answer by at least explaining some ways that I've used file format structures in reversing.</p> <p>First of all, a reverse engineer "in the workforce" always has some goal. For example, a malware analyst working at an antivirus company may analyze a sample to:</p> <ol> <li>Learn how the same works</li> <li>Learn novel techniques that it used to defeat the antivirus system</li> </ol> <p>Reverse engineering is simply learning about how a given system works. A file format is part of this system, and as such, simply learning about how the file format works, what its magic value is, what type of data is stored there, what the header consists of, and so on are all part of the reverse engineering process for some projects.</p> <p>One project that I worked on involved learning how the PE format header of some files differed from the PE format header of other files. In doing this, I needed to find out why the Windows operating system would properly load certain PE files, and would refuse to load other PE files, based on some data modifications in the PE file headers.</p> <p>This project was not open source, so I cannot go into too much detail, but I can tell you that people who want to prevent reverse engineering will use tools/algorithms called "packers" and "software protectors" and one component of these tools is that they will obstruct, corrupt, or otherwise mutate the data in the PE header on disk. One example of why someone would do this is because the PE header has a list of all external libraries and functions which will be called by the executable. This list is called <code>IMAGE_IMPORT_DESCRIPTOR</code> for each DLL such as kernel32.dll and ntdll.dll which has a list of <code>IMAGE_IMPORT_BY_NAME</code> (can also be ordinal imports) which lists out all of the functions to be used by the executable. An easy way to learn about how a program works is to simply view this list of imports because if a program will use networking, there will be networking imports, if it uses cryptography, there will be crypto imports, and so on.</p> <p>So to prevent this, software packers and protectors will often destroy this table on-disk and then rebuild it dynamically after the program is run. In order to effectively analyze the program, reverse engineers often have to dump the program after it is loaded in memory and rebuild the tables with a tool like ImpRec. Having a solid understanding of the PE file format makes this task possible.</p> <p>In the case of my aforementioned project, I needed to find out when a bit was set in a header member, why the OS would treat the file differently than if that bit was cleared. This involved learning the file format, then using WinDbg as a kernel debugger to find out why <code>NtCreateProcess</code> would not load certain files.</p> <p><strong>Example 2</strong></p> <p>I had a file parser that I needed to test for security vulnerabilities. One of the parser's main jobs is to read the file format header data structures, interpret them, and then act upon that data. Think of what happens when Adobe Photoshop opens up a JPEG file, for example. For this task, I had to study the documentation for the file format to better understand what those data structures did, then I wrote a custom fuzzing tool to inject arbitrary malformed data into the headers in an attempt to exploit the parser application.</p>
22805
2019-12-23T02:19:47.637
<p>I'm new to reverse engineering and I have started to study the anatomy of specific file formats, specifically PE right now. I really enjoy learning the different parts of the files and the different flags. </p> <p>I was just wondering, what are practical uses of this in the work force of reverse engineering?</p> <p>I know they probably serve some purpose but I am really new to this field and I was wondering when you employed this knowledge before. </p>
Importance of learning file structures for reverse engineering?
|binary-analysis|elf|pe|
<p>The first line of your file contains device information - it seems you are reading <a href="http://www.phoenixtm.com/en/products/data-loggers/" rel="nofollow noreferrer">HT DataLogger</a>'s data. From the quick glance, I conclude, this device measures temperature.</p> <p>Subsequent data looks like an <em>array of floats</em> - one can deduce it from <code>41</code>'s and <code>42</code>'s in each <code>4</code>-byte block (&quot;reasonable&quot; float numbers usually start with them when written in hex).</p> <p>To read the data, just take any <code>4</code>-byte, block starting with an address divisible by <code>4</code> and use <a href="https://www.binaryconvert.com/result_float.html" rel="nofollow noreferrer">this site</a>. However, as you may notice, the order of bytes in each <code>4</code>-byte block has to be different than just &quot;left to right&quot;, that is, so-called <em>big endian</em>.</p> <p>Knowing that each number has to start with either <code>41</code> or <code>42</code> (otherwise resulting numbers would be too high or too low to reflect the temperature), you can conclude that, in fact, number <code>ABCD</code> really means <code>BADC</code>, so it's <em>little endian</em> encoding with respect to each <code>2</code> bytes.</p> <p>For example, if you want to decode <code>01 41 33 33</code>, you want to convert the number <code>41 01 33 33</code> to decimal format (that is ~<code>8.075</code> Celcius degrees).</p> <p>Modifying data is rather straightforward - hex editors provide very easy way to do it; just highlight relevant bytes and start typing.</p> <p><strong>Edit:</strong> it is also possible (and more likely) that the numbers are stored in <em>little endian</em> encoding, assuming that the first one begins at address <code>0012h</code>. In such a case, <code>0x421</code> (<code>21 04 00 00</code>) is probably the size of the float array.</p>
22812
2019-12-23T12:03:46.240
<p>I am so newbie about this matter. </p> <p>I have a file XXXX.record file that contains a data. </p> <p>When I open the file </p> <p><a href="https://i.stack.imgur.com/zfRHY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zfRHY.png" alt="enter image description here"></a></p> <p>How can I read this data and modify the values? </p> <p>thanks. </p> <p><a href="https://i.stack.imgur.com/KY8WZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KY8WZ.png" alt="enter image description here"></a></p>
I want to modify the data
|debugging|hex|
<p>Yep, I think I've seen a similar case before. It happens very rarely, but because you can do some stunts at the C preprocessor level as well as at the linker level, this happens to work.</p> <p>In this case I looked it up in the 3790.1830 DDK (Windows 2003 Server) and several newer WDKs and SDKs.</p> <h3>Windows 2000/XP target (<code>3790.1830/inc/w2k/winbase.h</code> and <code>3790.1830/inc/wxp/winbase.h</code>)</h3> <pre><code>WINBASEAPI BOOL WINAPI CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue, WAITORTIMERCALLBACK Callback, PVOID Parameter, DWORD DueTime, DWORD Period, ULONG Flags ) ; </code></pre> <h3>Windows 2003/Vista/7 target (<code>3790.1830/inc/wnet/winbase.h</code> and <code>6001.18002/inc/api/WINBASE.H</code> and <code>7600.16385.1/inc/api/WINBASE.H</code>)</h3> <pre><code>WINBASEAPI BOOL WINAPI CreateTimerQueueTimer( __deref_out PHANDLE phNewTimer, __in_opt HANDLE TimerQueue, __in WAITORTIMERCALLBACK Callback, __in_opt PVOID Parameter, __in DWORD DueTime, __in DWORD Period, __in ULONG Flags ) ; </code></pre> <h3>With the Windows 8.1 SDK ...</h3> <p>... this API moved into another header: <code>Include/um/threadpoollegacyapiset.h</code> (check out <a href="http://www.geoffchappell.com/studies/windows/win32/apisetschema/index.htm" rel="nofollow noreferrer">this study on API sets</a>).</p> <pre><code>WINBASEAPI BOOL WINAPI CreateTimerQueueTimer( _Outptr_ PHANDLE phNewTimer, _In_opt_ HANDLE TimerQueue, _In_ WAITORTIMERCALLBACK Callback, _In_opt_ PVOID Parameter, _In_ DWORD DueTime, _In_ DWORD Period, _In_ ULONG Flags ); </code></pre> <p>... so no change up until this point (other than adopting SAL2 annotations).</p> <p>For the Windows 10 SDKs 10.0.10240.0, 10.0.16299.0, 10.0.17134.0, 10.0.17134.0, 10.0.17763.0, 10.0.18362.0 it still has the same order for the arguments as for Windows 8.1. <strong>So it stands to reason you ran into a documentation issue rather than an actual change here.</strong></p> <p>There is <a href="https://github.com/MicrosoftDocs/sdk-api/pulls?utf8=%E2%9C%93&amp;q=is%3Apr+CreateTimerQueueTimer" rel="nofollow noreferrer">no pending or old (and closed) pull request mentioning this function</a>, so you may want to consider sending one.</p>
22816
2019-12-23T15:39:53.620
<p>I was reading <a href="https://docs.microsoft.com/en-us/windows/win32/api/threadpoollegacyapiset/nf-threadpoollegacyapiset-createtimerqueuetimer" rel="nofollow noreferrer">a man page</a> about CreateTimerQueueTimer.</p> <pre><code>BOOL CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue, WAITORTIMERCALLBACK Callback, PVOID DueTime, DWORD Period, DWORD Flags, ULONG Parameter ); </code></pre> <p>The doc states:</p> <blockquote> <p>Period</p> <p>The period of the timer, in milliseconds. If this parameter is zero, the timer is signaled once.</p> </blockquote> <p>So I needed to set this to 0 to avoid the callback to be executed periodically. The problem was that modifying the <code>period</code> value has no effect on periodicity. Once loaded in OllyDBG, Olly reconstructed the arguments and the call giving me this function signature :</p> <pre><code>BOOL CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue, WAITORTIMERCALLBACK Callback, ULONG Parameter, PVOID DueTime, DWORD Period, DWORD Flags ); </code></pre> <p>Notice that the <code>parameter</code> argument changed position, and thus all my patches was useless. I guess this error might be due to an old version of the API where the <code>Parameter</code> argument was in 4th position, but I can be wrong. Also, I can't find old WinAPIs to confirm my sayings. Am I guessing right or am I missing something?</p>
CreateTimerQueueTimer arguments differs from WinAPI
|assembly|malware|winapi|calling-conventions|
<p>You must have been looking at the wrong representation.</p> <p>Opening the file with a plain graphics viewer shows that it indeed contains "maps", in a 2-byte-per-block format and with a fixed width of 128 bytes/64 blocks:</p> <p><a href="https://i.stack.imgur.com/1UOhe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1UOhe.png" alt="image courtesy of a most basic bitmap viewer"></a></p> <p>The first 514 bytes seem to contain some other kind of data but after that every two bytes form one single map block. You'll have to compare these word values against a running game to find out what they represent.</p> <p>Finding the bitmap text "D.P. Gray 1994" in the map leads me to believe you are looking at <a href="https://en.wikipedia.org/wiki/Nitemare_3D" rel="noreferrer">Nitemare 3D</a>, and with that information you can find <em>several</em> map editors, such as the one at <a href="http://wolf3d.darkbb.com/t1981-nitemare-3d-mapeditor" rel="noreferrer">http://wolf3d.darkbb.com/t1981-nitemare-3d-mapeditor</a>, which conveniently also tells you the same details I describe above (do note that that post is from 2011).</p> <p><sup>It took me less than 5 minutes to recognize "the format", and another 5 or so to google "D.P. Gray 1994".</sup></p>
22818
2019-12-23T20:13:36.333
<p>I've been messing around in visual studio for half an hour trying to figure out how to properly display maps from a file, but all I can output is hot garbage, all I know is that the maps are 64x64, can someone help me with this?</p> <p><a href="https://drive.google.com/file/d/1E1hCQaqfR5at0pkKgbKuyt7RhMua9IYC/view?usp=sharing" rel="nofollow noreferrer">map file</a></p>
can someone help me with this map format?
|c++|file-format|
<p><code>IDA</code> results look pretty good. I believe that the signature of <code>main</code> comes from any kind of <code>FLIRT</code> or other function recognitions - It detects that the function is <code>main</code>, and therefore gives it the default main signature. it looks like <code>foo</code> disassembled well. You can configure yourself the signature by pressing <code>y</code> on the function call. You must understand that the whole process is very heuristic, and this info does not appear anywhere in the binary.</p> <p>I saw it several times in <code>IDA</code>, that it creates a good signature for a function but sometimes calls it with extra/missing parameters. I believe it's a bug, rather than something configurable.</p>
22827
2019-12-26T02:29:09.133
<p>I'm testing several decompilers against the following <code>C</code> code</p> <pre><code> static int bar(int i) { return ++i; } static int apply(int (*fun)(int), int i) { return i % fun(i); } static int foo(int (*app)(int (*fun)(int), int), int i) { return i / app(bar, i); } int main() { return foo(apply, 7); } </code></pre> <p>which is compiled by just <code>clang test.c</code>.</p> <pre><code>; main 0x0 push rbp 0x1 mov rbp, rsp 0x4 sub rsp, 0x10 0x8 mov dword ptr [rbp-0x4], 0x0 0xf mov rdi, @apply 0x19 mov esi, 0x7 0x1e call foo 0x23 add rsp, 0x10 0x27 pop rbp 0x28 ret ; foo 0x30 push rbp 0x31 mov rbp, rsp 0x34 sub rsp, 0x20 0x38 mov [rbp-0x8], rdi 0x3c mov [rbp-0xc], esi 0x3f mov eax, [rbp-0xc] 0x42 mov rcx, [rbp-0x8] 0x46 mov esi, [rbp-0xc] 0x49 mov rdi, @bar 0x53 mov [rbp-0x10], eax 0x56 call rcx 0x58 mov edx, [rbp-0x10] 0x5b mov [rbp-0x14], eax 0x5e mov eax, edx 0x60 cdq 0x61 mov esi, [rbp-0x14] 0x64 idiv esi 0x66 add rsp, 0x20 0x6a pop rbp 0x6b ret </code></pre> <p>I was aware of some limits in argument/parameter detection (from the response to <a href="https://reverseengineering.stackexchange.com/questions/22634/struct-reconstruction-in-decompilers">another question</a>). But each decompiler seems, in one way or another, have inconsistency in the type system of its decompiled language (I think they all try to decompile to <code>C</code> or pseudo-<code>C</code>).</p> <p><code>IDA v.7.4.191122</code> (evaluation version) gives:</p> <pre><code>int __cdecl main(int argc, const char **argv, const char **envp) { return foo(apply, 7LL, envp); } __int64 __fastcall foo(int (__fastcall *a1)(__int64 (__fastcall *)(), _QWORD), unsigned int a2) { return (unsigned int)((int)a2 / a1(bar, a2)); } </code></pre> <p>I don't show results of <code>bar</code> and <code>apply</code> because there was already an inconsistency here: IDA detects that <code>foo</code> is called with 3 arguments in <code>main</code>, but then it concludes that <code>foo</code> has actually 2 parameters.</p> <p>Next, <code>Ghidra v9.1.build.2019-oct-23</code>:</p> <pre><code>void main(void) { foo(apply,7); return; } ulong foo(code *param_1,uint param_2,undefined8 param_3) { int iVar1; iVar1 = (*param_1)(bar,(ulong)param_2,param_3,param_1); return (long)(int)param_2 / (long)iVar1 &amp; 0xffffffff; } </code></pre> <p>which has an opposite opinion: <code>foo</code> is called in <code>main</code> with 2 arguments, but in its definition <code>foo</code> has 3 parameters.</p> <p><code>JEB v.3.8.0.201912242244</code> (evaluation version):</p> <pre><code>unsigned long main() { return foo(&amp;apply, 7L); } unsigned long foo(unsigned long param0) { unsigned int v0 = v1; param0(); return (unsigned long)(v0 / ((unsigned int)v2)); } </code></pre> <p>which gives a perfect result for <code>main</code>, but it then claims that <code>foo</code> is a function of just 1 parameters (and while it shows <code>param0()</code>, it keeps <code>param0</code> as <code>unsigned long</code>).</p> <p>Actually, the decompilation results are not correct (which is somehow understandable), but they are even inconsistent. Do I miss some configuration?</p>
Type inference inconsistency
|ida|decompilation|ghidra|jeb|
<p>The answer of @igor says about algorithm failures of IDA. Beside, I think you can use a function which is not type-able in the type system of the decompilation target language of IDA (I believe it's a subset of C), e.g.</p> <pre><code>int foo(void *f, int i) { return ((int (*)(void*, int))(f))(foo, i); } clang -c test.c </code></pre> <p>then IDA decompilers gives something likes</p> <pre><code>__int64 __fastcall foo(__int64 (__fastcall *a1)(__int64 (__fastcall *)(), _QWORD), unsigned int a2) { return a1(foo, a2); } </code></pre> <p>which is obviously not correct: <code>foo</code> is recognized simultaneously as a function of two params and one param.</p>
22833
2019-12-26T10:25:03.123
<p>I want to write a C function, such that <code>hex-rays</code> decompiler will fail on it. I want to do it for study purposes, and not for an actual anti-reversing method. Do you have any recommendations/approaches how can I write such a function, that will compile with <code>gcc</code> or similar compiler, but won't be decompilable by <code>hex-rays</code>?</p> <p><strong>EDIT:</strong> My goal is to make the code disassemblable, but not decompilable. I'm not looking for obfuscators that will hide the code completely, but a way to make IDA not to be able to decompile. for example, by somehow messing with the stack pointer. </p>
Methods for preventing IDA decompiler
|ida|c|hexrays|decompile|
<p>You were almost there. </p> <blockquote> <p>But they have to point to exactly the same address so this "cmp" instruction that comes after it will succeed</p> </blockquote> <p>This statement is incorrect. Not addresses are being compared, but the data at each. The code, starting from <code>.text:00C21094</code> compares <code>13</code> subsequent bytes at <code>byte_C23018</code> with their counterparts at <code>loc_C23024</code>.</p> <p>So, to get the correct password, we have to investigate them. It's easy to see, that at the start of the program, they are not the same, so they have to be modified at some point. The only place where it happens is the loop at <code>loc_C2107F</code>. It <code>xor</code>s subsequent letters of your password with the letters of "<code>G00D job!</code>" string. As you have pointed out, password has to have length <code>5</code>, including <code>\n</code> character, so it makes sense that the loop only uses first four bytes of the password.</p> <p>But <code>xor</code> is invertible operation; in other words, if <code>A xor B = C</code>, then <code>A = C xor B</code>, since <code>B xor B = 0</code> and <code>A xor 0 = A</code>. </p> <p>In your case, <code>A</code> is the password you are providing, <code>B</code> is the "<code>G00d job!</code>" string, and <code>C</code> is the string at <code>loc_C23024</code>. So, to find relevant <code>A</code> you just need to <code>xor</code> <code>B</code> with <code>C</code>.</p>
22835
2019-12-26T12:59:22.710
<p>I'm trying to understand the behaviour of the code below so I can determine what input will trigger the "YOU DID IT !~!" string (at the end of the program instructions):</p> <pre> .text:00C21034 Buf= byte ptr -6Ch .text:00C21034 var_68= byte ptr -68h .text:00C21034 var_4= dword ptr -4 .text:00C21034 .text:00C21034 push ebp .text:00C21035 mov ebp, esp .text:00C21037 sub esp, 6Ch .text:00C2103A mov eax, ___security_cookie .text:00C2103F xor eax, ebp .text:00C21041 mov [ebp+var_4], eax .text:00C21044 push ebx .text:00C21045 push offset aPleaseEnterThe ; "Please enter the password: " .text:00C2104A call sub_C21006 .text:00C2104F xor ebx, ebx .text:00C21051 push ebx .text:00C21052 call ds:__acrt_iob_func .text:00C21058 push eax ; File .text:00C21059 lea eax, [ebp+Buf] .text:00C2105C push 64h ; MaxCount .text:00C2105E push eax ; Buf .text:00C2105F call ds:fgets .text:00C21065 lea ecx, [ebp+Buf] .text:00C21068 add esp, 14h .text:00C2106B lea edx, [ecx+1] .text:00C2106E .text:00C2106E loc_C2106E: ; CODE XREF: sub_C21034+3F↓j .text:00C2106E mov al, [ecx] .text:00C21070 inc ecx .text:00C21071 test al, al .text:00C21073 jnz short loc_C2106E .text:00C21075 sub ecx, edx .text:00C21077 cmp ecx, 5 .text:00C2107A jnz short loc_C210C3 .text:00C2107C mov [ebp+var_68], bl .text:00C2107F .text:00C2107F loc_C2107F: ; CODE XREF: sub_C21034+5E↓j .text:00C2107F mov eax, ebx .text:00C21081 and eax, 3 .text:00C21084 mov al, [ebp+eax+Buf] .text:00C21088 xor byte_C23018[ebx], al .text:00C2108E inc ebx .text:00C2108F cmp ebx, 0Ah .text:00C21092 jb short loc_C2107F .text:00C21094 mov ecx, offset byte_C23018 .text:00C21099 mov edx, offset loc_C23024 .text:00C2109E mov eax, [ecx] .text:00C210A0 cmp eax, [edx] .text:00C210A2 jnz short loc_C210C3 .text:00C210A4 mov eax, [ecx+4] .text:00C210A7 cmp eax, [edx+4] .text:00C210AA jnz short loc_C210C3 .text:00C210AC movzx eax, byte ptr [ecx+8] .text:00C210B0 cmp al, [edx+8] .text:00C210B3 jnz short loc_C210C3 .text:00C210B5 push offset aYouDidIt ; "YOU DID IT !~!\r\n" .text:00C210BA call sub_C21006 .text:00C210BF xor eax, eax .text:00C210C1 jmp short loc_C210D0 .text:00C210C3 ; --------------------------------------------------------------------------- .text:00C210C3 .text:00C210C3 loc_C210C3: ; CODE XREF: sub_C21034+46↑j .text:00C210C3 ; sub_C21034+6E↑j ... .text:00C210C3 push offset aOhhhhNooTryAga ; "Ohhhh noo... try again.\r\n" .text:00C210C8 call sub_C21006 .text:00C210CD xor eax, eax .text:00C210CF inc eax </pre> <p><br> <strong>NOTE:</strong><br> The goal here is to find the correct input. I know that I can just put the IP where I want and make the program print it.</p> <p><br> <strong>What I understood so far:</strong></p> <p>The program asks for input in this instruction:</p> <pre> .text:00C2105F call ds:fgets </pre> <p>After that, it runs a loop that counts how many chars are in the input, including the "new line" char at the end (when the user gives input and presses "enter"):</p> <pre> .text:00C2106E loc_C2106E: ; CODE XREF: sub_C21034+3F↓j .text:00C2106E mov al, [ecx] .text:00C21070 inc ecx .text:00C21071 test al, al .text:00C21073 jnz short loc_C2106E </pre> <p>Then, it subtracts the address of the last input char and the address of the first input char to determine the input's length:</p> <pre> .text:00C21075 sub ecx, edx .text:00C21077 cmp ecx, 5 .text:00C2107A jnz short loc_C210C3 </pre> <p>If the input length is different than 5 (including the "new line" char), then it jumps to this label that prints out "Ohhhh noo... try again." and terminates the program:</p> <pre> .text:00C210C3 push offset aOhhhhNooTryAga ; "Ohhhh noo... try again.\r\n" .text:00C210C8 call sub_C21006 </pre> <p>if the input length is exactly 5 (including the "new line" char), then it proceeds to this instruction that removes the "new line" char from the end of the input string, such that instead of 'A' hexa, there will be '0' hexa (bl initially have a value of 0):</p> <pre> .text:00C2107C mov [ebp+var_68], bl </pre> <p>So, if the input's length is 5 (including the new line char), it should proceeds to the code below. It's a loop that runs 10 times. ebx is initially 0, and it keeps running until ebx = 0A hexa = 10 decimal:</p> <pre> .text:00C2107F loc_C2107F: ; CODE XREF: sub_C21034+5E↓j .text:00C2107F mov eax, ebx .text:00C21081 and eax, 3 .text:00C21084 mov al, [ebp+eax+Buf] .text:00C21088 xor byte_C23018[ebx], al .text:00C2108E inc ebx .text:00C2108F cmp ebx, 0Ah .text:00C21092 jb short loc_C2107F </pre> <p>Now, the thing about this loop is that the following instruction guarentees that eax will always have values in the range 0-3:</p> <pre> .text:00C21081 and eax, 3 </pre> <p>So, supposed I entered the input "G00D", that loop will XOR each char of the input string with every char of the string "G00D job!" (byte_C23018 that appears in the XOR instruction stores this string, see "P.S" at the end of the post), here is a demo of this loop ('20h' is the ascii value of the "space" char):</p> <pre> eax = 0 | eax = 1 | eax = 2 | eax = 3 | eax = 0 | eax = 1 |etc G XOR G = 0|0 XOR 0 = 0| 0 XOR 0 = 0|D XOR D = 0|G XOR '20h' = g|0 XOR j = z|etc </pre> <p>After that loop I'm starting to struggle.<br> The 2 labels in the code below are 6 addresses away from each other:</p> <pre> .text:00C21094 mov ecx, offset byte_C23018 .text:00C21099 mov edx, offset loc_C23024 </pre> <p>But they have to point to exactly the same address so this "cmp" instruction that comes after it will succeed:</p> <pre> .text:00C210A0 cmp eax, [edx] </pre> <p>Otherwise - the condition for the "jnz" instruction below is met, and it jumps to that label that prints the "oh no try again" string:</p> <pre> .text:00C210A2 jnz short loc_C210C3 </pre> <pre> .text:00C210C3 push offset aOhhhhNooTryAga ; "Ohhhh noo... try again.\r\n" .text:00C210C8 call sub_C21006 </pre> <p>Any suggestions or ideas? did I understand something wrong?</p> <p>Thanks in advance!</p> <p><br> <strong>P.S:</strong><br> This is where the "G00D job!" is stored. Notice that the "G" is '47h'</p> <pre> .data:00C23018 byte_C23018 db 47h ; DATA XREF: sub_C21034+54↑w .data:00C23018 ; sub_C21034+60↑o .data:00C23019 a00dJob db '00D job!',0 .data:00C23022 align 4 .data:00C23024 .data:00C23024 loc_C23024: ; DATA XREF: sub_C21034+65↑o .data:00C23024 add eax, 62657D71h .data:00C23029 sub esp, [edx] .data:00C2302B inc ebx .data:00C2302C arpl [eax], ax </pre> <p>And if I input "G00D", it stores it here:</p> <pre> debug007:00BBF8A0 db 47h ; G debug007:00BBF8A1 db 30h ; 0 debug007:00BBF8A2 db 30h ; 0 debug007:00BBF8A3 db 44h ; D </pre>
Finding the correct input of an executable to print out the flag. IDA 7
|ida|disassembly|assembly|crackme|
<p>I've made some research and found that the textures uses one of these formats, depending on the 2 bytes value the texture has (10, 11, 4, 5, 0 or 2063): </p> <p>"DXT1, DXT3, A8R8G8B8, A4R4G4B4, R5G6B5, A1R5G5B5"</p>
22838
2019-12-27T01:33:31.643
<p>I've been researching on how to modify the textures of Crazy Taxi 3 for a while now and I have pretty much hit a brick wall.<br> The game stores its texture assets in <code>.art</code> files, which, from what I understand, contain several textures in each of them, due to there being many banks of textures. There is also a <code>Sprites</code> folder containing these files that indicate the same.<br> A quick Google search led me to believe that this may be the <a href="http://fileformats.archiveteam.org/wiki/ART_(AOL_compressed_image)" rel="nofollow noreferrer">AOL Image Format</a> used in its software, however AOL 9.0 kept throwing errors when trying to open the files. No dice.<br> After searching more I found that <a href="http://fileformats.archiveteam.org/wiki/ART_(PFS:_First_Publisher)" rel="nofollow noreferrer">PFS: First Publisher used this extension as well for its clip art</a>. The files do not exactly match <a href="http://fileformats.archiveteam.org/wiki/ART_(PFS:_First_Publisher)" rel="nofollow noreferrer">the structure documented in this wiki</a>, but every .art file has something that looks like a table of information <em>in that structure</em> at the start, and then possibly image data. I have also observed that the string <code>GXTX</code> is repeated many times, may suggest that it might be a pointer of the beginning of a new image.<br> Other than that, I have no idea how this file format may work. It seems like it is uncompressed image data, however after opening it in many programs I have given up and need help.</p> <hr> <p><strong>UPDATE 1</strong>:<br> I have found a great tool called <a href="https://forum.xentax.com/blog/?p=821" rel="nofollow noreferrer">Texturefinder</a> that helped me figure out that these textures are compressed with DXT, however I am unsure which version, as half of a certain texture bank may look great in DXT1, while another half looks jumbled until I switch to DXT3 or 5. The container format possibly has information on which algorithm to use in a table before the images, as at the start of each texture file there is plenty of non-image data, or at least data that this tool can not decide. Here are a few examples of this working in one algorithm vs the other:</p> <p><a href="https://i.stack.imgur.com/Ukd5l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ukd5l.png" alt="DXT1a @ 512px width"></a> <a href="https://i.stack.imgur.com/jhI9l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jhI9l.png" alt="DXT3 @ 256px width"></a></p> <p>So, here is an updated list of what I have gathered:</p> <ul> <li><code>.art</code> files contain the string <code>GXTX</code> many times, usually followed by about 12 bytes that have small values (something like <code>80 00 80 00 00 80 00 00 01 00 05 00</code>), likely an image separator</li> <li><a href="http://wiki.polycount.com/wiki/DXT" rel="nofollow noreferrer">The files contain many textures compressed with DXT</a></li> <li>Textures may be compressed with differing forms of DXT (possibly DXT1 and DXT3)</li> <li>Textures in banks may have differing widths/heights</li> <li>Every texture bank has a sizeable amount of non-image data at the start</li> <li>The textures are upside down</li> </ul> <p><a href="https://anonfiles.com/35E491Jcn5/samples_zip" rel="nofollow noreferrer">Here are some more samples for comparison.</a></p>
Understanding proprietary game texture/image format (.art)
|file-format|
<p>Since you code seems to be un-optimized, you have to manually follow the memory access manually. In your case, you have to apply this structure offset (T) at 0x000000000040111C (rax), 0x0000000000401122 (rax) and 0x000000000040112C (rdx). AFAIK, there's no easy way to define a local variable as a pointer to a structure and automatically show reference to the structure. Unless you are working with hexrays decompiler.</p>
22851
2019-12-28T01:17:12.550
<p>In the following function <code>foo</code></p> <pre><code>.text:0000000000401110 foo proc near .text:0000000000401110 .text:0000000000401110 var_8 = qword ptr -8 .text:0000000000401110 .text:0000000000401110 push rbp .text:0000000000401111 mov rbp, rsp .text:0000000000401114 mov [rbp+var_8], rdi .text:0000000000401118 mov rax, [rbp+var_8] .text:000000000040111C mov ecx, [rax] .text:000000000040111E mov rax, [rbp+var_8] .text:0000000000401122 add ecx, [rax+4] .text:0000000000401125 movsxd rax, ecx .text:0000000000401128 mov rdx, [rbp+var_8] .text:000000000040112C add rax, [rdx+8] .text:0000000000401130 pop rbp .text:0000000000401131 retn .text:0000000000401131 foo endp </code></pre> <p>which is actually</p> <pre><code>struct S { int a; int b; long long c; }; int foo(struct S *s) { return s-&gt;a + s-&gt;b + s-&gt;c; } </code></pre> <p>I've defined the struct <code>S</code> in IDA (via Shift-F9/Ins...), how can I specify that <code>rdi</code> is the pointer to the base of the struct, so that the disassembly becomes something like this</p> <pre><code>... .text:0000000000401118 mov rax, [rbp+var_8] .text:000000000040111C mov ecx, [p0.a] .text:000000000040111E mov rax, [rbp+var_8] .text:0000000000401122 add ecx, [p0.b] .text:0000000000401125 movsxd rax, ecx .text:0000000000401128 mov rdx, [rbp+var_8] .text:000000000040112C add rax, [p0.c] ... </code></pre> <p>There is a <a href="https://reverseengineering.stackexchange.com/questions/3148/ida-setting-a-register-as-a-basepointer-to-struct">similar question</a> but it applies for the case where, for example <code>rbx</code> is the base pointer and fields are accessed via <code>[rbx+offset]</code>. In my case, <code>rdi</code> is the base pointer but fields are not accessed via <code>[rdi+offset]</code>.</p>
IDA: apply function parameter as struct pointer
|ida|struct|
<p>It seems like your <code>Ghidra</code> decompilation went wrong. Are you using the last version of <code>Ghidra</code>? </p> <p>The output that I get in the latest version is:</p> <pre><code>undefined8 entry(void) { size_t sVar1; char local_118 [9]; char local_10f; long local_10; local_10 = *(long *)___stack_chk_guard; _printf("Enter the password...\n"); _fgets(local_118,0x100,*(FILE **)___stdinp); sVar1 = _strcspn(local_118,"\n"); local_118[sVar1] = '\0'; sVar1 = _strlen(local_118); if ((int)sVar1 == 10) { if (local_118[0] == local_10f) { _printf("Correct!\nthe password is: %s\n",local_118); } else { _wrong_password(); } } else { _wrong_password(); } if (*(long *)___stack_chk_guard == local_10) { return 0; } /* WARNING: Subroutine does not return */ ___stack_chk_fail(); } </code></pre> <p>Which makes much more sense. I would guess that your <code>Ghidra</code> version has some problems with parsing the <code>plt</code>/imports. Upgrade to the latest version and check again. </p> <p>As for your second question: When you don't understand the decompilation, you should always go to the disassembly. </p> <pre><code> 100000e42 MOVSX EAX,byte ptr [RBP + local_118] 100000e49 MOVSX ECX,byte ptr [RBP + local_10f] 100000e50 CMP EAX,ECX </code></pre> <p>You can see that there is a compersion between two bytes from the stack. </p> <p>In this case <code>RBP + local_118</code> is the pointer to the stack location of the user string. <code>0x118 - 0x10f = 9</code> => You are looking at the last character (index 9 of the string is the 10th character). So the comparison is between the first and the last char. </p>
22862
2019-12-29T05:32:41.617
<p>Here is the Ghidra decompiler output for a crackme problem. Specifically, <a href="https://crackmes.one/crackme/5d443bb533c5d444ad3018b3" rel="nofollow noreferrer">this one</a>:<br> Code:</p> <pre><code>undefined8 entry(undefined8 param_1,char *param_2) { int iVar1; size_t sVar2; char *pcVar3; char *pcVar4; char local_118 [9]; char local_10f; long local_10; local_10 = *(long *)___stdinp; _strcspn("Enter the password...\n",param_2); _printf(local_118,0x100,*(undefined8 *)_fgets); pcVar3 = "\n"; sVar2 = _strlen(local_118); pcVar4 = local_118; local_118[sVar2] = '\0'; iVar1 = dyld_stub_binder(); if (iVar1 == 10) { if (local_118[0] == local_10f) { _strcspn("Correct!\nthe password is: %s\n",local_118); } else { _wrong_password(pcVar4,pcVar3); } } else { _wrong_password(pcVar4,pcVar3); } if (*(long *)___stdinp == local_10) { return 0; } </code></pre> <p>I'm having some trouble understanding the output.</p> <ol> <li>the printf and strcspn functions seem to be switched? </li> <li>the <code>local_10f</code> variable is never initialized, and yet is still used to compare to the passcode.</li> <li>I know from reading the solution, that as long as the first and last characters are the same, and the length is 10, then the passcode will work. How does "dyld_stub_binder" check for length? Where do the first and last characters get compared?</li> </ol> <p>Thanks for any help.</p>
Weird Ghidra decompiler output for simple crack me
|ghidra|
<p>The solution that I found is:</p> <p><code>analyze(currentProgram)</code></p> <p>Just after the disassembly. </p>
22880
2019-12-31T13:28:09.713
<p>I'm interested in open a binary file (<code>.bin</code>, without arch info), and analyze it with <code>analyzeHeadless.bat</code> (Ghidra version without GUI). </p> <p>I know what is the architecture of the file, so I pass it as a flag to the analyzer.</p> <p>My command line is: <code>analyzeHeadless.bat &lt;project_location&gt; &lt;project_name&gt; -import &lt;my_file&gt; -processor &lt;my_known_processor&gt; -postscript &lt;my_script.py&gt; -scriptPath &lt;path&gt;</code></p> <p>my_script.py is:</p> <pre><code>for block in getMemoryBlocks(): current = block.getStart().getOffset() end = block.getEnd().getOffset() addr = currentProgram.getAddressFactory().getAddress(hex(current).replace('L', '')) disassemble(addr) current +=1 func = getFirstFunction() print("First func is: " + str(func)) </code></pre> <p>I try to disassemble every address (looks like Ghigra doesn't do it itself), and after that I want to print the first function.</p> <p>The problem is: <code>func</code> appears to be <code>None</code>.</p> <p>But if after the headless execution I open the project in the GUI <code>Ghidra</code>, and execute:</p> <pre><code>func = getFirstFunction() print("First func is: " + str(func)) </code></pre> <p>It works and gets me the function.</p> <p>Any ideas what am I doing wrong? I guess there is some analysis that runs in the background and created the functions. How can I run it in my python script? </p>
Ghidra Headless Analyzer - Create Functions
|python|ghidra|
<p><a href="http://www.keystone-engine.org/keypatch/" rel="nofollow noreferrer">Keypatch</a> is a plugin for IDA that uses keystone to assemble instructions for patching. It works much better than IDA's old built-in assembler, and it should be able to handle 64-bit operands.</p>
22886
2020-01-02T05:59:48.067
<p>I am trying to patch a function in 64-bit Windows DLL to load data I have inserted into the resource table of the DLL. I want to insert code something like this:</p> <pre><code>mov r8d, 0Ah ; lpType mov edx, 0h ; lpName xor ecx, ecx ; hModule call cs:FindResourceW mov [rsp+148h+var_B8], rax ; using existing var_B8 to store hResInfo mov rdx, [rsp+148h+var_B8] ; hResInfo xor ecx, ecx ; hModule call cs:LoadResource mov [rsp+148h+var_B0], rax ; using existing var_B0 to store hResData mov rcx, [rsp+148h+var_B0] ; hResData call cs:LockResource ; data is now in location referenced by RAX register </code></pre> <p>The first problem seems to be the "Assemble" function in IDA pro doesn't handle 64-bit operands, so instructions such as mov r8d, 0Ah I have to assemble by hand and patch via bytes.</p> <p>However I am not sure how to easily generate the call cs:FindResourceW instruction. While the "assembly" feature generates code the disassembly shows it as gibberish, call instruction "assembled" at 00000272D0B83B4C:</p> <pre><code>.text:00000272D0B83B3F mov r8d, 0Ah .text:00000272D0B83B45 mov edx, 0 .text:00000272D0B83B4A xor ecx, ecx .text:00000272D0B83B4A ; --------------------------------------------------------------------------- .text:00000272D0B83B4C db 9Ah ; š .text:00000272D0B83B4D db 40h ; @ .text:00000272D0B83B4E db 94h ; ” .text:00000272D0B83B4F db 0BDh ; ½ .text:00000272D0B83B50 db 0D0h ; Ð .text:00000272D0B83B51 db 6 .text:00000272D0B83B52 db 0 .text:00000272D0B83B53 db 89h ; ‰ .text:00000272D0B83B54 db 84h ; „ .text:00000272D0B83B55 ; --------------------------------------------------------------------------- .text:00000272D0B83B55 and al, 89h .text:00000272D0B83B55 ; --------------------------------------------------------------------------- .text:00000272D0B83B57 db 45h ; E .text:00000272D0B83B58 db 8 </code></pre> <p>To currently assembly I am taking location from import table:</p> <pre><code>.idata:00000272D0BD9440 ; HRSRC __stdcall FindResourceW(HMODULE hModule, LPCWSTR lpName, LPCWSTR lpType) .idata:00000272D0BD9440 extrn FindResourceW:qword </code></pre> <p>Subtracting location where I will insert my code, and subtract 6.</p> <pre><code> 272D0B83B4A (Code location) -272D0BD9440 (Import table location) -6 =========== 00 05 58 F0 </code></pre> <p>I am then patching with FF 15 followed by the result in reverse order such as inserting bytes:</p> <pre><code>FF 15 F0 58 05 00 </code></pre> <p>This works but is time consuming, is there any better patching option for inserting call instructions quickly.</p>
How to Insert Call to Already Imported Function in amd64 Windows DLL using IDA Pro?
|ida|patching|amd64|
<p>As part of ASLR, operating systems use code relocation tables embedded in an executable to change the location where an executable image is located.</p> <p>If you remove the relocation tables (or generate an executable without it to begin with) the operating system will not be able to relocate the executable image, however other images also loaded to the same process's memory address will still be relocated.</p> <p>Additionally, an OS may implement/support ASLR related executable file flag to opt-in or out of ASLR and again depending on the OS and user configuration, executables that don't support ASLR may still be randomized.</p> <p>Visual studio have two related flags, <code>/FIXED</code> and <code>/DYNAMICBASE</code>, for including relocation tables and opting-in for ASLR.</p> <p>On GCC, <code>-fPIE</code> is used to enable relocation tables (position independent executable).</p>
22889
2020-01-02T10:47:20.487
<p>I want to create an executable that keeps the same virtual address during different execution runs. </p> <p>This is definitely possible because I've seen these files in CTFs(Capture the flag) where the player has to use a buffer overflow, to rewrite the return address in order to execute a "secret" function.</p> <p>So, is there a way to tell GCC to generate an executable that "doesn't" allow memory randomization on execution?</p> <p>Or maybe I'm thinking it all wrong. Any info you can share to point me on the right direction will be appreciated.</p>
How to create an executable that keeps the same virtual address on different runs
|c|dynamic-analysis|executable|
<p>Depending on the original source, the class definition could be entirely in the header file. Class definitions are no longer useful in object files as the compiler already knows how fields and methods are laid out.</p> <p>You have to guess the original definition. Keep in mind that you already have guessed a lot when reverting via hex-rey as C++ allows preprocessing, templating and macro expansion. This means that the types you are using are of the correct size, but have lost their semantic meaning that in the original source code they might have: e.g. custom typedefs are usually lost. </p>
22906
2020-01-04T20:51:04.040
<p>I have a complicated question to ask so I will try my best to be clear.</p> <p>I have this binary I am trying to reverse that came with a pdb file. I have dumped the compilands of the binary to begin with.</p> <p>I want to reproduce the source code of the binary as close to the original as possible so I see in the first compiland that somefile.obj(let's call it that) consists of ../file_path/somefile.cpp and ../compile_path/xlocale</p> <p>I then dumped the line numbers for somefile.cpp and using ida pro as my disassembler and hex-rays decompiler as a guide.</p> <p>From the source lines, hex-rays and some manual work I have managed to recreate somefile.cpp to the point that it's diasassembly is identical to the original file's one.</p> <p>The somefile.cpp consists of an empty constructor and destructor and a few function implementations.</p> <p>My problem is, the dumped compiland does not show a somefile.h as part of the object but the functions in somefile.cpp are methods of a somefile class (I got the entire class definition from the pdb). I can always create my own header file and put the class definition in there but that's not the purpose.</p> <p>So, my question is: where does the original somefile.cpp get the class definition from? Is there a way I can get such information at all, or do I have to guess?</p> <p>I am very sorry for the long text. </p>
Class definition
|ida|msvc|
<p>Try to do <code>ctrl + A</code> - select all and then press <code>D</code> to disassemble. good chance it will solve your problem. </p>
22911
2020-01-05T16:29:24.960
<p>I was trying to understand the <code>IsDebuggerPresent()</code> function exported by kernelbase.dll by importing the file on Ghidra. But Ghidra can't show me the proper disassembly or decompilation of function even though disassembly works fine in PE Bear? What could be the issue? I don't know if this is the proper place to post this so please guide me to a place if it isn't. Thanks!</p> <p><a href="https://i.stack.imgur.com/RiU7s.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RiU7s.jpg" alt="Ghidra Disassembly/Decompilation Output"></a></p> <p><a href="https://i.stack.imgur.com/CKEEh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CKEEh.jpg" alt="PE Bear Disassembly Output"></a></p>
Ghidra can't Decompile kernelbase.dll exported functions?
|disassembly|dll|ghidra|
<p>The original one was a native executable and this one is build in .NET by <a href="https://github.com/pjbgf/dotnet-ildasm/blob/master/src/dotnet-ildasm/dotnet-ildasm.csproj#L23" rel="nofollow noreferrer">utilizing</a> a <a href="https://www.mono-project.com/docs/tools+libraries/libraries/Mono.Cecil/" rel="nofollow noreferrer">Mono.Cecil</a> library to get the assembly information so if I would have to answer your first question I would answer - no, they are not the same.</p> <p>Not sure about your second question as original one was Windows executable so there's no point installing it on Linux. I would use the one you linked dotnet-ildasm or <a href="https://github.com/mono/ikdasm" rel="nofollow noreferrer">ikdasm</a> from the Mono project.</p> <p>Why are you so focused on having the "original" one?</p>
22915
2020-01-05T18:09:06.290
<p>I would like to use ildasm on Linux. The original one, that comes with the .NET SDK and can be found on Windows e.g. at <code>c:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\</code>.</p> <p>I found <a href="https://www.nuget.org/packages/dotnet-ildasm/" rel="nofollow noreferrer">dotnet-ildasm</a> and managed to install it on my Ubuntu 18.04. But I am unsure if this is the same as the "original" one.</p> <ul> <li>Is dotnet-ildasm the same as Microsoft ildasm?</li> <li>Did someone mangage to install the Microsoft ildasm on Linux?</li> </ul>
ildasm on Linux: "original" ildasm.exe same as dotnet-ildasm?
|linux|.net|
<p>Firstly you would like to know if someone has already implemented the required protocol to read that flash memory model. You should try to search on your favorite engine queries like "'model' dump" or "dumping 'model' with buspirate" , where 'model' IS the name of your chip.</p> <p>If you cannot find anything, you Will have to do It by yourself.</p> <p>I just searched for "MX25L1606E datasheet" and i found, in the first result, all the needed details about your particular chip: <a href="https://www.google.es/url?sa=t&amp;source=web&amp;rct=j&amp;url=https://www.macronix.com/Lists/Datasheet/Attachments/7465/MX25L1606E,%25203V,%252016Mb,%2520v1.9.pdf&amp;ved=2ahUKEwikqZ6DwfPmAhUDDewKHbtZBTUQFjAAegQIBRAB&amp;usg=AOvVaw2RuJPF7rRLWzADjhovrUpM" rel="nofollow noreferrer" title="datasheet">datasheet</a></p> <p>There you can find that It uses the SPI protocol, and the supported commands (READ, WRITE, etc) as well as others that may be important.</p> <p>Now you need a hardware that can speak that protocol. Bus pirate is great and has documentation. You just need to read the datasheet to discover which SPI Mode is used.</p> <p>You could also repurpose an Arduino UNO or Arduino UNO clone board (or any more powerful Arduino version). Arduino UNO can speak SPI. As an example, I did that to read the <a href="https://github.com/pedro-javierf/dsaver" rel="nofollow noreferrer">SPI flash of Nintendo DS cartridges</a> for example. You would like to use the ICSP pins of the Arduino to connect to your memory, send commands and receive data, store it into the arduino memory, and send it to your PC over the serial connection of the Arduino.</p> <p>Please note that Arduino (UNO) boards have little memory available, so you need to read the memory in smaller chunks.</p>
22927
2020-01-07T08:42:18.593
<p>I am currently working on a Netgear router having MX25L1606E rom chip, my goal is to extract firmware for reverse engineering but <a href="https://flashrom.org/Flashrom" rel="nofollow noreferrer">flashrom</a> don't have support for it. So question is how someone can read data from rom by making their own program or script. I've tried with buspirate but I don't know what would be specific SPI mode settings to read data out of this chip. </p>
If flashrom tool don't have support for rom chip what are the ways you can extract data without it?
|hardware|
<p>I've completed the process with a fixed version of de4dot.</p> <p>Fixed version:<a href="https://board.b-at-s.info/index.php?/topic/9731-de4dot-cryptophoenixreactor-fixed-by-ivancitooz/" rel="nofollow noreferrer">fixed by ivancitooz</a></p>
22946
2020-01-08T14:39:26.683
<p>There is an <strong>application</strong> that has been <strong>obfuscation</strong> to learn. So in an unpack me style. In the first stage I would unpack with de4dot. <strong>After</strong> you unpack, the running application <strong>stops</strong> working.</p> <p>dump and then again when I want to do the same process again stops working.</p> <p>Even when I want to <strong>fix</strong> it with <strong>Universal_Fix</strong>, a result <strong>doesn't</strong> change.</p> <p>When I look at the application with <strong>dnSpy</strong>, there is no problem. Codes can be read. It remains stuck in the <strong>main</strong> <strong>function</strong> when I want to run it. And it returns the following error.</p> <p><a href="https://i.stack.imgur.com/niyRS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/niyRS.png" alt="enter image description here"></a></p> <p>That's where he hangs out.</p> <p><a href="https://i.stack.imgur.com/3schy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3schy.png" alt="enter image description here"></a></p> <p>Error returning when I want to continue.</p> <p>What should I do about this?</p> <p>I apologize for my bad English.</p>
Error After de4dot - Application Does Not Start
|obfuscation|deobfuscation|de4dot|
<p>That's extremely common. Sometimes Hex-Rays recognizes these patterns, sometimes it doesn't. Get used to recognizing them visually, writing a comment if necessary, and moving on.</p>
22955
2020-01-09T13:45:31.473
<p>While trying to decompile an application with Hex-Ray 7.0, I stumbled upon the problem that in nearly all cases, what seems to be a certain inline function will not be recognised, which bloats the code base and makes it really hard to read. The function seems to be strcpy or something similar. Is there a way to have the Decompiler change the mentioned parts to an inline function? Or can I do it manually somehow? Here's a screenshot to illustrate my issue:<a href="https://i.stack.imgur.com/D1Hiw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D1Hiw.png" alt="" /></a></p> <p>Thanks a lot in advance!</p>
Hex-Ray Decompiler: inline function not recognized
|ida|hexrays|decompiler|
<p>Having such code the first thing to do is to analyze what part is the obfuscation algorithm and what's the actual code. Here' it's not that difficult as all the code is on top. So let's analyze it step by step:</p> <pre><code>var norm = ["cookie", "toUTCString",... </code></pre> <p>defines an array with string that will be used in the application. Having them in an array and not in the code makes the code more difficult for human to understand but the machine will still managed to parse the code correctly. </p> <p>So we have an array...</p> <p>What's next? Following the array there's this function</p> <pre><code>(function(value, count) { var fn = function(selected_image) { for (; --selected_image;) { value["push"](value["shift"]()); } }; fn(++count); })(norm, 144); </code></pre> <p>What it does it creates a function that can shuffle an array and in the last line <code>(norm, 144)</code> it is being executed with our aforementioned array of strings and the constant value of <code>144</code> that will be used to count the number of rounds of the shuffling (<code>+1</code> -> <code>fn(++count)</code>). </p> <p>So after this we no longer know the order of string in our defined array <code>norm</code>. In order to know it we would have to execute those two instructions (<strong>it might be dangerous if you don't understand what your are doing</strong>) or mimic similar behavior in another language and get the result. (<code>["object", "exports", "./IPv6",...]</code>).</p> <p>So now comes the third part of the obfuscation - this function:</p> <pre><code>var $ = function(i, fn) { i = i - 0; var id = norm[i]; return id; }; </code></pre> <p>It simply defines a function named <code>$</code> that, when passed an argument <code>i</code> returns the string from our shuffled array <code>norm</code>.</p> <p>Now comes the actual code part. Whenever you see code like this <code>$("0x1b1")</code> you would have to replace it by running (or simulating) the call to function <code>$</code> with the argument and get the result. In this case it would be for <code>0x1b1 = "hxxps://www.bitonclick.com/jump/next.php?r=1967903"</code> (without xx - a proper address) and for example for <code>$("0x114") = "FuckAdBlock"</code>. And so on...</p> <p>Doing this of all the calls you would get all of the code extracted, but going over this manually can be mundane and error prone so it would be nice to have some kind of automated way of performing this activities.</p> <p>Doing that (not even for the whole file) would allow to more easily understand the code but from parts of it, it looks like it might be injecting some ads on the page (it might not be the only purpose of it) - as one can see in the strings "Ad", "FuckAdBlock" and some <code>iframes</code>.</p>
22956
2020-01-09T14:39:19.887
<p>i have this code i'm trying to deobfuscate <a href="https://pastebin.com/g5mHpWE4" rel="nofollow noreferrer">https://pastebin.com/g5mHpWE4</a></p> <p>I used <a href="https://beautifier.io/" rel="nofollow noreferrer">https://beautifier.io/</a> and <a href="http://www.jsnice.org/" rel="nofollow noreferrer">http://www.jsnice.org/</a></p> <p>but the result is still not good, current code: <a href="https://pastebin.com/whfqanxx" rel="nofollow noreferrer">https://pastebin.com/whfqanxx</a></p> <p>much remains coded example: <code>window [$ (" 0x128 ")] [$ (" 0x11 ")] [$ (" 0x7 ")]</code></p> <p>Is it possible to leave this code 100% clean?</p>
Is it possible to completely reverse this code?
|obfuscation|deobfuscation|javascript|
<p>Not Sure i selected uxtw in this post Right Clicked and Search Google For UXTW<br> the First Hit is <a href="http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0802a/SUB_addsub_ext.html" rel="nofollow noreferrer">Arm Documentation</a></p> <pre><code>SUB Wd|WSP, Wn|WSP, Wm{, extend {#amount}} ; 32-bit general registers SUB Xd|SP, Xn|SP, Rm{, extend {#amount}} ; 64-bit general registers extend Is the extension to be applied to the second source operand: 32-bit general registers Can be one of UXTB, UXTH, LSL|UXTW, UXTX, SXTB, SXTH, SXTW or SXTX. If Rd or Rn is WSP then LSL is preferred rather than UXTW, and can be omitted when amount is 0. In all other cases extend is required and must be UXTW rather than LSL. 64-bit general registers Can be one of UXTB, UXTH, UXTW, LSL|UXTX, SXTB, SXTH, SXTW or SXTX. If Rd or Rn is SP then LSL is preferred rather than UXTX, and can be omitted when amount is 0. In all other cases extend is required and must be UXTX rather than LSL. </code></pre> <p>sxtw is signed extend word 8000->ffff8000<br> uxtw isunsigned extend word 8000->00008000 </p> <p><a href="https://thinkingeek.com/2016/10/23/exploring-aarch64-assembler-chapter-3/" rel="nofollow noreferrer">quoting from another relevent hit</a> </p> <blockquote> <p>Extending operators</p> <p>Extending operators main purpose is to widen a narrower value found in a register to match the number of bits for the operation. An extending operator is of the form kxtw, where k is the kind of integer we want to widen and w is the width of the narrow value. For the former, the kind of integer can be U (unsigned) or S (signed, i.e. two’s complement). For the latter the width can be B, H or W which means respectively byte (least 8 significant bits of the register), half-word (least 16 significant bits of the register) or word (least significant 32 bits of the register).</p> <p>This means that the extending operators are uxtb, sxtb, uxth, sxth, uxtw, sxtw.</p> <p>These operators exist because sometimes we have to lift the range of the source value from a smaller bit width to a bigger one. In later chapters we will see many cases where this happens. For instance, it may happen that we need to add a 32-bit register to a 64-bit register. If both registers represent two’s complement integers then</p> <p>add x0, x1, w2, sxtw // x0 ← x1 + ExtendSigned32To64(w2)</p> <p>There is some kind of context that has to be taken into account when using these extension operators. For instance, the two instructions below have slight different meanings:</p> <p>add x0, x1, w2, sxtb // x0 ← x1 + ExtendSigned8To64(w2) add w0, w1, w2, sxtb // w0 ← w1 + ExtendSigned8To32(w2)</p> <p>In both cases the least significant 8 bits of w2 are extended but in the first case they are extended to 64 bit and in the second case to 32-bit. Extension and shift</p> <p>It is possible to extend a value and then shift it left 1, 2, 3 or 4 bits by specifying an amount after the extension operator. For instance</p> <p>mov x0, #0 // x0 ← 0 mov x1, #0x1234 // x0 ← 0x1234 add x2, x0, x1, sxtw #1 // x2 ← x0 + (ExtendSigned16To64(x1) &lt;&lt; 1) // this sets x2 to 0x2468 add x2, x0, x1, sxtw #2 // x2 ← x0 + (ExtendSigned16To64(x1) &lt;&lt; 2) // this sets x2 to 0x48d0 add x2, x0, x1, sxtw #3 // x2 ← x0 + (ExtendSigned16To64(x1) &lt;&lt; 3) // this sets x2 to 0x91a0 add x2, x0, x1, sxtw #4 // x2 ← x0 + (ExtendSigned16To64(x1) &lt;&lt; 4) // this sets x2 to 0x12340</p> <p>This may seem a bit odd and arbitrary at this point but in later chapters we will see that this is actually useful in many cases.</p> <p>This is all for today.</p> </blockquote> <p>here is a sample unicorn python emulation</p> <pre><code>#code modified from unicorn sample from __future__ import print_function from unicorn import * from unicorn.arm64_const import * print ( "Register X30 on start = 0x10\n" "Register W0 on start = 0x02\n" "Emulate 5 ARM64 instructions that follows\n" "ADD X30, X30, W0,UXTW#0\n" "ADD X30, X30, W0,UXTW#1\n" "ADD X30, X30, W0,UXTW#2\n" "ADD X30, X30, W0,UXTW#3\n" "ADD X30, X30, W0,UXTW#4\n" "Register X30 on end = 0x10+0x2+0x4+0x8+0x10+0x20 == 0x4e" ) CODE = b"\xDE\x43\x20\x8B\xDE\x47\x20\x8B\xDE\x4b\x20\x8B\xDE\x4f\x20\x8B\xDE\x53\x20\x8B" ADDRESS = 0x10000 def test_arm64(): try: mu = Uc(UC_ARCH_ARM64, UC_MODE_ARM) mu.mem_map(ADDRESS, 2 * 1024 * 1024) mu.mem_write(ADDRESS, CODE) mu.reg_write(UC_ARM64_REG_X30, 0x10) mu.reg_write(UC_ARM64_REG_W0, 2) for i in range (ADDRESS,ADDRESS + len(CODE),4): mu.emu_start(i, i + 4) x30 = mu.reg_read(UC_ARM64_REG_X30) w0 = mu.reg_read(UC_ARM64_REG_W0) print("&gt;&gt;&gt; x30 = 0x%x w0 = 0x%x" %(x30,w0)) except UcError as e: print("ERROR: %s" % e) if __name__ == '__main__': test_arm64() </code></pre> <p>emulation results</p> <pre><code>:\&gt;python uniaarch64.py Register X30 on start = 0x10 Register W0 on start = 0x02 Emulate 5 ARM64 instructions that follows ADD X30, X30, W0,UXTW#0 ADD X30, X30, W0,UXTW#1 ADD X30, X30, W0,UXTW#2 ADD X30, X30, W0,UXTW#3 ADD X30, X30, W0,UXTW#4 Register X30 on end = 0x10+0x2+0x4+0x8+0x10+0x20 == 0x4e &gt;&gt;&gt; x30 = 0x12 w0 = 0x2 &gt;&gt;&gt; x30 = 0x16 w0 = 0x2 &gt;&gt;&gt; x30 = 0x1e w0 = 0x2 &gt;&gt;&gt; x30 = 0x2e w0 = 0x2 &gt;&gt;&gt; x30 = 0x4e w0 = 0x2 </code></pre> <p>when you start with -0x2 in W0 see the extended results</p> <pre><code>&gt;&gt;&gt; x30 = 0x10000000e w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0x30000000a w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0x700000002 w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0xefffffff2 w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0x1effffffd2 w0 = 0xfffffffe </code></pre> <p>SXTW and -2</p> <pre><code>&gt;&gt;&gt; x30 = 0xe w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0xa w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0x2 w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0xfffffffffffffff2 w0 = 0xfffffffe &gt;&gt;&gt; x30 = 0xfffffffffffffff0 w0 = 0xfffffffe </code></pre> <p>SXTW and 2</p> <pre><code>&gt;&gt;&gt; x30 = 0x12 w0 = 0x2 &gt;&gt;&gt; x30 = 0x16 w0 = 0x2 &gt;&gt;&gt; x30 = 0x1e w0 = 0x2 &gt;&gt;&gt; x30 = 0x2e w0 = 0x2 &gt;&gt;&gt; x30 = 0x30 w0 = 0x2 </code></pre>
22962
2020-01-10T16:39:42.033
<p>Sorry, if this question seems stupid, but I am new in arm64 and next 2 assembly lines seriously damaged my brain:</p> <pre><code>LDR W0, [X30,W0,UXTW#2] ADD X30, X30, W0,UXTW </code></pre> <p>I have readed <a href="http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0802a/LDR_imm_fpsimd.html" rel="nofollow noreferrer">docs</a>, used google with different keywords, but it seems like everything connected to assembly is written by machines to machines..</p> <p>I understood that it patches return address of subroutine, but what <code>UTXW#2</code> is and how does it affect on <code>LDR</code> is hard to undertand.</p> <p>Could somebody explain me "magic" which happens in this 2 lines?</p>
LDR specifier combination UXTW
|assembly|arm|arm64|
<p>I did something similar on the past, here is the idea you need to carry:</p> <ol> <li><p>You create the python script that you want to execute and obfuscate:</p> <pre><code>print('Some string') </code></pre></li> <li><p>Another script opens the previous script, encrypts the content and <code>base64</code> the encryption, and finally put in a variable like:</p> <pre><code>text = "cHJpbnQoJ1NvbWUgc3RyaW5nJyk=" </code></pre></li> <li><p>On another python file, you stick the text variable and a routine for decryption and decode the base64.</p></li> <li><p>Use the method <code>eval()</code> for execute the previous decrypted and decoded string.</p></li> </ol> <p>This is not perfect but at least you have something to play with and explore. </p>
22972
2020-01-12T13:13:50.547
<p>I have a software with an embedded python interpreter. The software can open upon startup a given <code>.py</code> script and execute it. Let's assume that in my python environment I can't open other files, and I can't use external tools like <code>Cython</code> </p> <p>I want to obfuscate the script. My only demand is that the <code>payload</code> part of the file (my custom business logic) could not be opened in a text editor and plain-text read. </p> <p>I could imagine the flow of the script will be de-obfuscation/decryption of a payload, that resides within the <code>.py</code> file as the first step and then executing it. </p> <p>I can store within the script any encryption key, and I don't care that the decryption part will be visible and that it can be easily reproduced.</p> <p>Any ideas how can I make that happen?</p>
Python self decryption script, as mean of obfuscation
|encryption|python|obfuscation|
<p>Paweł Łukasik is correct.</p> <p>Disassembling the code fragment using Ghidra can be done in 3 steps:</p> <ol> <li><p>Selecting the architecture (which you have already done)</p></li> <li><p>Highlighting the bytes to disassemble</p></li> </ol> <p><a href="https://i.stack.imgur.com/gZ6l9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gZ6l9.png" alt="Highlight and press D"></a></p> <ol start="3"> <li>Press "D" as Paweł stated or right click and select "disassemble"</li> </ol> <p><a href="https://i.stack.imgur.com/RLiVB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RLiVB.png" alt="disassembled fragment"></a></p>
22974
2020-01-12T17:03:42.860
<p>I'm trying to get the disassembly of a very small binary file available <a href="https://1drv.ms/u/s!AsYP2RqBWCWrokQmsi4oN2igDK2m?e=fnrfXV" rel="nofollow noreferrer">here</a>. This file is cropped from part of another executable binary. </p> <p>When I open it with <code>r2</code> it automatically recognizes the architecture and can provide me with the diassembly: </p> <p><a href="https://i.stack.imgur.com/ZMnUy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZMnUy.png" alt="enter image description here"></a></p> <p>With Ghidra however, it cannot find the architecture automatically and I have to manually specify the language: </p> <p><a href="https://i.stack.imgur.com/KTrmH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KTrmH.png" alt="enter image description here"></a></p> <p>Even then, I'm getting the following as the disassembly:</p> <p><a href="https://i.stack.imgur.com/uq58V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uq58V.png" alt="enter image description here"></a></p> <p>I'm very surprised by how poor NSA's Ghidra is performing in such scenario compared to the open source radare2. Can someone describe what's going on and how can I fix it? </p>
Why Ghidra doesn't load the disassembly correctly while radare2 does?
|disassembly|ghidra|
<p>It is being used when there's a mismatch between type sizes in the decompiled code and Ghidra cannot show you that the whole variable is being modified. </p> <p>Your <code>PUCHAR</code> - since it is a pointer and this is (probably) 64-bit is 8 bytes. But analyzing the disassembly Ghidra sees that only 4 bytes are being set to 0 in this line (for example a 32 bit register is used).</p> <p>One of the fix you can apply is by correcting the type of <code>local_res8</code> (<kbd>CTRL+L</kbd>) but it might be the case that the type is ok, and in fact only lower 32-bits are being set..</p>
22983
2020-01-13T14:43:55.647
<p>What does _0_4_ mean in ghidra?</p> <p><a href="https://i.stack.imgur.com/HA5Ku.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HA5Ku.png" alt=""></a></p>
Ghidra what's the meaning of _0_4_
|ghidra|
<p>Its been a couple months since this was asked, but there is also another option. If you can manually calculate the jumps then its possible to specify these into Ghidra to override its default behaviour.</p> <p>There is a script called <code>SwitchOverride</code>, which can be found in the script manager window. Below is the documentation from the script:</p> <blockquote> <p>This script allows the user to manually specify the destinations of an indirect jump (switch)  to the decompiler, if it can't figure out the destinations itself or does so incorrectly.  To use, create a selection that contains:  the (one) instruction performing the indirect jump to override  other instructions whose addresses are interpreted as destinations of the switch  then run this script</p> </blockquote>
22985
2020-01-13T15:20:22.817
<p>I'm currently analyzing a function that has a lot of indirect jumps looking like the following.</p> <p>LEA R10,[0x142000000]</p> <p>(some instructions that dont change R10)</p> <p>JMP R10</p> <p>The Ghidra decompiler just treats the indirect jump as a call and doesnt give any meaningful output. How do I go ahead and analyze a function like that? I guess ideally I would just like to change the JMP R10 instruction to JMP 0x142000000 in this example, however if I cant just do that since the opcode is larger and other jumps would no longer align.</p>
Ghidra analyzing hardcoded indirect jumps
|decompilation|ghidra|
<p>The best way to debug this in my opinion is to use WinDbg from <a href="https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk" rel="nofollow noreferrer">Windows SDK</a> or <a href="https://www.microsoft.com/en-us/p/windbg-preview/9pgjgd53tn86?activetab=pivot:overviewtab" rel="nofollow noreferrer">WinDbg Preview</a> from Windows Store. In Windows it is not possible to attach two debuggers to the same process. WinDbg supports easily debugging .NET and native processes.</p> <p>To access .NET functionality you can run commands:</p> <pre><code>.loadby sos clr </code></pre> <p>More details of the .NET extensions <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/sos-dll-sos-debugging-extension" rel="nofollow noreferrer">here</a> Improved .NET debugging with sosex 3rd party extension <a href="http://stevestechspot.com/SOSEXV40NowAvailable.aspx" rel="nofollow noreferrer">here</a> Common commands for WinDbg thematically grouped <a href="http://www.windbg.info/doc/1-common-cmds.html" rel="nofollow noreferrer">here</a> </p> <p>There is some learning curve to use it fully effectively but once learned it is extremely powerful debugger for .NET and native code.</p> <p>If must use x64dbg then you would require a plugin that supports .NET, the currently available plugins are listed here: <a href="https://github.com/x64dbg/x64dbg/wiki/Plugins" rel="nofollow noreferrer">https://github.com/x64dbg/x64dbg/wiki/Plugins</a></p>
22996
2020-01-14T09:31:42.190
<p>I'm trying to reverse an application that is using a DLL that i'm interested in.</p> <p>I can properly disassemble the application itself with DnSpy, as it is a .Net application, and I can disassemble the used DLL with IDA, as it's a native C shared library.</p> <p>I am using x64dbg as a debugger, and i would like to see the interactions between the application and the DLL. I can properly break on the DLL by loading the .Net app into x64Dbg, and waiting for a DLL call, and it's fine.</p> <p>But the fact that x64dbg does not support .Net syntax make it very weird to play with when the flow came back from the DLL to the application, and i would like to do the following:</p> <ul> <li><p>Use the DnSpy build-in debugger to see what's going on on a high level with the .Net application.</p></li> <li><p>And use x64dbg attached to the DLL to take a look at it whenever it is call by the application.</p></li> </ul> <p>But i can't manage to do that, since the root process (the .Net application) cannot be debugged by two debugger at the same time.</p> <p>How can i setup x64dbg to intercept the DLL without attaching it to the .Net process ?</p> <p>Is it even possible to do that ?</p> <p>Or maybe I'm unaware of some magic tools that would help me ?</p> <p>Any idea ?</p> <p>Thanks :)</p>
Attach one debugger to a DotNet application, and a second one to a loaded DLL
|ida|dll|.net|
<p>When I assembled the code, the offending instruction was:</p> <pre><code>0x6c 40 ff d1 call rcx </code></pre> <p>You will need to use <a href="https://www.hex-rays.com/products/ida/support/idadoc/489.shtml" rel="nofollow noreferrer">Change Stack Pointer</a> command in IDA to fix this in disassembly. As per IDA documentation:</p> <ul> <li>This command allows you to specify how the stack pointer (SP) is modified by the current instruction. </li> <li>You cannot use this command if the current instruction does not belong to any function. </li> <li>You will need to use this command only if IDA was not able to trace the value of the SP register. </li> <li>Usually IDA can handle it but in some special cases it fails. An example of such a situation is an indirect call of a function that purges its parameters from the stack. In this case, IDA has no information about the function and cannot properly trace the value of SP. </li> <li>Please note that you need to specify the difference between the old and new values of SP.</li> <li>The value of SP is used if the current function accesses local variables by [ESP+xxx] notation. </li> </ul> <p>This can also be verified by removing the call rcx instruction and confirming it removes the SP Analysis failed error in IDA.</p> <p>Based on the 2nd version with uploaded ELF the problem is IDA hasn't detected the end of the function correctly.</p> <p><a href="https://i.stack.imgur.com/t02bN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t02bN.png" alt="enter image description here"></a></p> <p>Right clicking the function <strong>foo</strong> in Functions view and selecting Edit function and changing the end address to 0:000000000000006C fixes the SP analysis problem.</p> <p>When trouble shooting SP Analysis failures also enabling Stack Pointer in <strong>Options</strong> | General and selecting <strong>Stack Pointer</strong> can help you determine cause of problems, this will show the stack pointer value in green text to the left of instructions.</p> <p><a href="https://i.stack.imgur.com/KDiqP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KDiqP.png" alt="enter image description here"></a></p> <p>The 3rd sample provided it's the same issue. To find the end of function, switch to Text view find the offset of retn and add one, for example the end of function in the last sample provided is 5D5.</p> <p>The root cause of the problem is the redundant REX prefix (0x40) at the start. Normal 64-bit function prologs start with 55 48 89 E5 so IDA tries to create a function at address 1 which interferes with the actual function at 0 and makes it stop after one instruction. This planned to be fixed in future releases of IDA.</p>
23005
2020-01-14T23:11:29.380
<p>I'm testing my toy obfuscating C compiler against IDA's decompiler, but IDA refuses always functions (then the decompilation is not possible). For example, at one of lowest-levels of obfuscating, a function likes</p> <pre><code>int foo(int i) { return i; } </code></pre> <p>is compiled to</p> <pre><code>0x0 40 55 push rbp 0x2 48 89 e5 mov rbp, rsp 0x5 41 56 push r14 0x7 41 57 push r15 0x9 48 83 ec 10 sub rsp, 0x10 0xd 40 89 bc 24 0c 00 00 00 mov [rsp+0xc], edi 0x15 48 8d 05 e4 ff ff ff lea rax, [rip-0x1c] 0x1c 44 8b bc 24 0c 00 00 00 mov r15d, [rsp+0xc] 0x24 44 8b b4 24 0c 00 00 00 mov r14d, [rsp+0xc] 0x2c 45 0f af fe imul r15d, r14d 0x30 44 89 f9 mov ecx, r15d 0x33 83 c1 01 add ecx, 0x1 0x36 44 8b b4 24 0c 00 00 00 mov r14d, [rsp+0xc] 0x3e 45 0f af f7 imul r14d, r15d 0x42 48 63 c9 movsxd rcx, ecx 0x45 49 63 d6 movsxd rdx, r14d 0x48 48 39 d1 cmp rcx, rdx 0x4b 0f 95 c1 setnz cl 0x4e 40 84 c9 test cl, cl 0x51 75 1c jnz 0x1c 0x53 44 8b bc 24 0c 00 00 00 mov r15d, [rsp+0xc] 0x5b 49 63 cf movsxd rcx, r15d 0x5e 44 8b bc 24 0c 00 00 00 mov r15d, [rsp+0xc] 0x66 44 89 ff mov edi, r15d 0x69 48 89 c6 mov rsi, rax 0x6c 40 ff d1 call rcx 0x6f 44 8b bc 24 0c 00 00 00 mov r15d, [rsp+0xc] 0x77 44 89 f8 mov eax, r15d 0x7a 48 83 c4 10 add rsp, 0x10 0x7e 41 5f pop r15 0x80 41 5e pop r14 0x82 40 5d pop rbp 0x84 c3 ret </code></pre> <p>I still don't understand why <a href="https://www.hex-rays.com/products/ida/support/idadoc/1368.shtml" rel="nofollow noreferrer">the stack frame analysis</a> can be failed for this case. There are only two groups of instructions modifying <code>rsp</code>, the first 5:</p> <pre><code>0x0 40 55 push rbp 0x2 48 89 e5 mov rbp, rsp 0x5 41 56 push r14 0x7 41 57 push r15 0x9 48 83 ec 10 sub rsp, 0x10 </code></pre> <p>and the last 5:</p> <pre><code>0x7a 48 83 c4 10 add rsp, 0x10 0x7e 41 5f pop r15 0x80 41 5e pop r14 0x82 40 5d pop rbp 0x84 c3 ret </code></pre> <p>and they actually make the stack pointer balanced.</p> <p>How can I fix that?</p> <p><em>Update</em>: @chentiangemalc suggests that it comes from <code>call rcx</code>, then I changed the obfuscating option to not generate such a call, and removed almost all other obfuscating options, following is an even simpler result</p> <pre><code>0x0 40 55 push rbp 0x2 48 89 e5 mov rbp, rsp 0x5 40 53 push rbx 0x7 48 83 ec 08 sub rsp, 0x8 0xb c1 ef 00 shr edi, 0x0 0xe 89 f8 mov eax, edi 0x10 81 c8 33 19 d0 39 or eax, 0x39d01933 0x16 89 f9 mov ecx, edi 0x18 81 e1 33 19 d0 39 and ecx, 0x39d01933 0x1e 0f af c1 imul eax, ecx 0x21 40 b9 33 19 d0 39 mov ecx, 0x39d01933 0x27 89 ca mov edx, ecx 0x29 f7 d2 not edx 0x2b 89 fb mov ebx, edi 0x2d 21 d3 and ebx, edx 0x2f f7 d7 not edi 0x31 21 f9 and ecx, edi 0x33 0f af d9 imul ebx, ecx 0x36 01 d8 add eax, ebx 0x38 81 c0 31 d6 93 7f add eax, 0x7f93d631 0x3e 40 b9 fb 89 99 8c mov ecx, 0x8c9989fb 0x44 0f af c1 imul eax, ecx 0x47 81 c0 f5 c4 23 fd add eax, -0x2dc3b0b 0x4d 48 8d 8c 24 04 00 00 00 lea rcx, [rsp+0x4] 0x55 40 89 01 mov [rcx], eax 0x58 48 8d 84 24 04 00 00 00 lea rax, [rsp+0x4] 0x60 40 8b 00 mov eax, [rax] 0x63 48 83 c4 08 add rsp, 0x8 0x67 40 5b pop rbx 0x69 40 5d pop rbp 0x6b c3 ret </code></pre> <p>but IDA complains always <code>sp-analysis failed</code> ((I've put the ELF <a href="https://send.firefox.com/download/a6e2224e532d962f/#7T05h7_HprqN7gprnr0-YA" rel="nofollow noreferrer">here</a>).</p> <p>Other tools like Ghidra or JEB Decompiler happily recognizes the function, though.</p> <p><em>Update</em>: the method of @chentiangemalc works perfectly. <s>for the example above, unfortunately there are cases where IDA is not happy (sample: <a href="https://send.firefox.com/download/af09a8b198096475/#lGtfN2XJRu3Q3KW9ESh6tw" rel="nofollow noreferrer">ELF</a>)</s>.</p>
Stack-pointer analysis failed
|ida|decompilation|obfuscation|decompiler|
<p>You can refer to this <a href="https://stackoverflow.com/questions/3819699/what-does-ds40207a-mean-in-assembly">answer</a> for the <code>DS</code> part.</p> <p>I believe the <code>nop</code> and <code>xchg</code> are only paddings. They appear after <code>ret</code>, and they aren't executed as part of the function.</p>
23019
2020-01-16T13:14:41.923
<p><a href="https://i.stack.imgur.com/rzSfT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rzSfT.png" alt="enter image description here"></a></p> <p>Hi guys, I'm just practising the difference between global and local variables and how they are represented in x86 assembly. I just don't understand the use of the ds segment register and the NOP slide at the end (nop and xchg ax, ax are the same thing).</p> <p>Thanks for your help! </p>
I don't understand the use of mov eax,ds:0x404004 and the NOP slide in this code I made
|x86|
<p>Actually it was so obvious - I just haven't read the C++ standard and was writing <code>throw()</code> specification thinking it would allow all exceptions - instead it turned out it was the exact opposite.</p> <p>And yes this <code>throw</code> function specification is what is causing those zero TryBlockMap with more than one Unwind entries. Here is a VC++ 6.0 (and later) compilable example (view dissasembly of <code>f</code>):</p> <pre><code>#include &lt;stdio.h&gt; struct B { int a, b; }; struct B1 { B1() {}; B1(const B1&amp; tmp) { a1 = tmp.a1; printf("B1::B1 copy constr\n"); } ~B1() { printf("~B1()\n"); } int a1, b1; }; struct A : B, B1 { int b, c; }; struct A f() throw(int) { struct A tmp; return tmp; } int main() { f(); } </code></pre> <p>With two unwind entries. The tricky part in that scenario is that <code>throw</code> specification is not added to the type of the function so even if you have debug symbols (PDB) - you still will have your head banging against the wall.</p> <p>EDIT: Actually the above example won't work for newer versions of MSVC - if you want to do it there you would need to add a <code>try</code> - <code>catch</code> block encapsulating the <code>f()</code> call.</p> <p>Also the <code>class A</code> and all of it's parents were a test case for <a href="https://reverseengineering.stackexchange.com/questions/24804/what-is-the-mdisp-field-in-rtti-for-throw-used-for">another question</a> related to the topic of C++ exception if you want to learn more but otherwise I don't think this exact structure is necessary to trigger the generation of FunctionInfo with zero TryBlocks. There just need to be something going on in <code>f</code> I think.</p>
23024
2020-01-16T21:17:16.830
<p>I'm trying to decompile an old binary (about 20 year old).</p> <p>The program uses exceptions.</p> <p>I found some FuncInfo but they do not contain any pTryBlockMap and nTryBlocks is 0.</p> <p>I've tried many options on the VC6 compiler but I could not get this result.</p> <p>The stack doesn't look like a regular stack:</p> <pre><code>... SEH handler scope table Try Level saved EBP return address </code></pre> <p>But it looks like:</p> <pre><code>... SEH handler Try level return address </code></pre> <p>Do you have any idea how to achieve this and why it would have been like that ?</p> <p>SEH Handler is :</p> <pre><code>MOV EAX,DAT_00412c90 JMP ___CxxFrameHandler </code></pre> <p>FuncInfo@00412c90</p> <pre><code>19930520 00000005 00412cb0 00000000 00000000 00000000 00000000 00000000 </code></pre>
VC 6 C++ Exception handling, nTryBlocks=0, pTryBlockMap=0 , how?why?
|decompilation|c++|callstack|
<p>The canonical source is the <a href="https://developer.arm.com/docs/ddi0487/latest/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile" rel="noreferrer">ARM Architecture Reference Manual</a>. If you prefer machine readable format, the <a href="https://developer.arm.com/architectures/cpu-architecture/a-profile/exploration-tools" rel="noreferrer">XML files are available too</a>. </p>
23030
2020-01-17T14:43:42.267
<p>I'm sorry for such as questions where answer would seem to be easily searched in google...</p> <p>Some time ago I have seen table/list of ARMv8 instructions with opcodes and it was perfect, but I lost link. Now I'm trying to find at least some sources where opcodes of instructions listed and can't.</p> <p>There're some C headers, where opcodes defined in non-readable form, lot of different scientific publications with 1k+ pages (containing no opcodes), etc., but I can't find simple list.</p> <p>Could somebody point me?</p>
ARMv8 (AArch64, ARM64) opcodes list
|assembly|arm|arm64|
<p>First off, <strong>you should never use <code>javap</code> when dealing with obfuscated applications</strong>, because <code>javap</code> is not designed to handle malicious bytecode, and can easily be thwarted in a number of ways. Luckily, the <a href="https://github.com/Storyyeller/Krakatau" rel="nofollow noreferrer">Krakatau disassembler</a> is specifically designed for working with obfuscated bytecode and can handle pretty much anything. (If you find anything that runs on the JVM and can't be disassembled, please file a bug). Luckily, in this case it disassembles without errors.</p> <p>In addition to the bytecode disassembler and assembler, Krakatau also contains a Java decompiler which is specifically designed for decompiling obfuscated bytecode. It's not particularly user friendly, but it can often decompile stuff that no other decompiler can handle. In this case, Krakatau was able to decompile your application without errors after some minor fixes.</p> <p>In order to decompile your app with Krakatau, I had to do two things:</p> <ul> <li>Fix a Python 2 unicode handling error (the <code>'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)</code> message you got) by changing <code>.decode()</code> to <code>.decode('utf8')</code>.</li> <li>Supply the Spigot library with the <code>-path</code> option. I had to modify the Spigot jar slightly first, to move the bukkit part to the right path (it expects classes at <code>org/bukkit/craftbukkit/entity/CraftPlayer</code>, but that class is located at <code>bukkit/craftbukkit/v1_15_R1/entity/CraftPlayer</code> in the Jar I downloaded).</li> </ul> <p>Anyway, once that was done, the obfuscated jar you provided decompiled without errors. Note that the jar makes use of <code>invokedynamic</code>, which can't be decompiled in general, since it is a bytecode feature that has no Java equivalent. In order to warn you of this, Krakatau outputs comments in the decompiled source like this:</p> <pre><code> label12: { try { if (!/*invokedynamic*/false) { break label12; } if (b) { break label12; </code></pre> <p>In cases like this, you need to consult the disassembled bytecode to see exactly what it is doing:</p> <pre><code>L14: iload 6 L16: ifne L8 L19: invokedynamic InvokeDynamic invokeStatic Method [c24] '\u200c\u2001\u2005\u2001' [u26] : '\ufb05\u58d7\ufb06\u0226\udb3d\u78ef\ufb09\u0226\ufb00\u58d5\udb3d\u221f\udb32' '()L\u2004\u2006\u2007\u2007;' L24: invokedynamic [id154] L29: invokedynamic InvokeDynamic invokeStatic Method [c24] '\u200c\u2001\u2005\u2001' [u26] : [nat157] L34: invokedynamic InvokeDynamic invokeStatic Method [c24] '\u200c\u2001\u2005\u2001' [u26] : '\ufb05\u58d7\ufb06\u0226\udb3d\u78ef\ufb09\u0226\ufb00\u58d5\udb3d\u221f\udb32' '()L\u2004\u2006\u2007\u2007;' L39: new '\u200b\u2007\u2006\u200d' L42: dup L43: aload 4 </code></pre> <p>As far as obfuscations go, the main obfuscations I noticed were a) renaming everything to unicode, and b) inserting dummy fields and a bunch of fake control flow branching on those fields. Here is an example of the latter in the decompiled output:</p> <pre><code> boolean b = \u200e\u200a; label0: { if (b) { break label0; } if (b) { break label0; } \u2005\u200c\u2005\u2009 = new java.util.HashMap(); if (!b) { } } </code></pre> <p>Note that the Krakatau decompiler performs a lot of analysis to simplify the control flow. It is no wonder that other decompilers would just give up when seeing complicated control flow like this.</p> <p>It is also notable that this is a fairly weak obfuscation. In particular, it creates a static field and branches on the value, but it never actually assigns to that field, so the field can just be replaced by a constant to simplify the bytecode. This reminds me a bit of bytecode I've seen that was obfuscated by ZKM, so it is possible that your friend was using ZKM.</p> <p>For example, after I patched the jar to replace the static fields with a constant <code>false</code> and decompiled it again, Krakatau's constant propagation was able to completely simplify away the fake control flow. Here's the decompiled version of the same function as above after replacing the field with <code>false</code>:</p> <pre><code>static { \u2005\u200c\u2005\u2009 = new java.util.HashMap(); } </code></pre>
23035
2020-01-17T17:15:11.707
<p>I've got a jarfile from a friend, he told me to put it thru an decompiler. So I did, but:</p> <ul> <li>JD-GUI basically spit out just the imports and didn't show any class data</li> <li>CFR dumped out stack trace on certain and created basically unusable Java code</li> <li>I didn't even try using JAD for it because it's using pattern matching for decompilation</li> <li><strong>The bytecode, according to the specification, is invalid</strong> because it contains incorrect entry for constant table</li> <li>JBE spit out a couple of errors and crashed, the same goes for fernflower</li> </ul> <p>Albeit all of that, <strong>I tried to execute it on a virtual machine - and it works!</strong> I'm literally swept off my knees looking at what happened there, and I believe this may be a fragment of code that is simply un-decompilable. I also did analyze the class file by hand, but everything seemed so contradictionary I eventually gave up. And, what is more interesting, <strong>I tried to use it along with multiple JRE versions starting with Java 13 and ending with Java 8 it worked in practice everywhere and I can't believe it</strong>.</p> <p><a href="http://kspalaiologos.baselinux.net/doc/unnamedObf.jar" rel="noreferrer">The jar file</a>.</p> <p>I've also uploaded the <a href="http://kspalaiologos.baselinux.net/doc/dump.java" rel="noreferrer">CFR output</a> (it's hillarious). I don't know really much about the obfuscator and the person who sent me the jar refuses to provide the further information, but I've got permission for redistributing and obviously decompiling it. Last bit of information I've got is the fact that the obfuscator is supposedly public and free-to-use, but I refuse to believe it (it could be though, unless I've been a victim of bluffing).</p> <p>How do I even tackle that? How is this, that the jar-file is almost completely obfuscated up until this point all the tooling that exists nowadays has severe problems with even outputting the bytecode assembly? It's not a very confidental piece of code and I'd most probably throw it away and forget about it, but I'm so curious on how it works, I've spent around two days trying to figure it out.</p> <p>Thanks in advance for any help.</p>
Dealing with heavily obfuscated Java, possibly on bytecode level
|obfuscation|java|deobfuscation|
<p>This is a great resource. You can find most of the material on SEI CERT website but the book is great.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/0321822137" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/Secure-Coding-2nd-Software-Engineering/dp/0321822137</a></p>
23038
2020-01-17T23:45:14.623
<p>I'm looking for a list of all vulnerabilities that can be present in C so I can practice them all.</p> <p>I found this: <a href="https://www.owasp.org/index.php/Category:C/C++" rel="nofollow noreferrer">Category:C/C++</a>, but it's not of much use.</p>
I'm looking for a list of C vulnerabilities like OWASP Top 10
|c|
<p>This would be typical to see in use of strtok function. Example code from <a href="https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm" rel="nofollow noreferrer">here</a></p> <pre><code>#include &lt;string.h&gt; #include &lt;stdio.h&gt; int main() { char str[80] = "This is - www.tutorialspoint.com - website"; const char s[2] = "-"; char *token; /* get the first token */ token = strtok(str, s); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, s); } } </code></pre> <p>Disassembly:</p> <pre><code>.LC0: .string " %s\n" main: push rbp mov rbp, rsp sub rsp, 112 movabs rax, 2338328219631577172 movabs rdx, 8463440690376286253 mov QWORD PTR [rbp-96], rax mov QWORD PTR [rbp-88], rdx movabs rax, 8102939320206389108 movabs rdx, 7885630523722066287 mov QWORD PTR [rbp-80], rax mov QWORD PTR [rbp-72], rdx movabs rax, 7598525184233975072 mov edx, 25972 mov QWORD PTR [rbp-64], rax mov QWORD PTR [rbp-56], rdx mov QWORD PTR [rbp-48], 0 mov QWORD PTR [rbp-40], 0 mov QWORD PTR [rbp-32], 0 mov QWORD PTR [rbp-24], 0 mov WORD PTR [rbp-98], 45 lea rdx, [rbp-98] lea rax, [rbp-96] mov rsi, rdx mov rdi, rax call strtok mov QWORD PTR [rbp-8], rax .L3: cmp QWORD PTR [rbp-8], 0 je .L2 mov rax, QWORD PTR [rbp-8] mov rsi, rax mov edi, OFFSET FLAT:.LC0 mov eax, 0 call printf lea rax, [rbp-98] mov rsi, rax mov edi, 0 call strtok mov QWORD PTR [rbp-8], rax jmp .L3 .L2: mov eax, 0 leave ret </code></pre> <p>The token = strtok(NULL, s); line is compiled with </p> <pre><code>mov edi,0 call strtok </code></pre> <p>You can quickly check/compare different compilers and their assembly output with the website <a href="https://godbolt.org/" rel="nofollow noreferrer">https://godbolt.org/</a></p>
23064
2020-01-20T23:58:46.000
<p>I'm working on a larger reversing project and came across this segment. I don't really understand what's going on here. There is no other way to proceed along the flow of control besides bypassing this block and jumping to 0x400d2d. Also noting that there are other locations in this program that call strtok with "reasonable" arguments, and I've bypassed those sections correctly. Would anyone share some wisdom I'm lacking? Thank you!</p> <pre><code>mov esi, 0x401018 // delimiter argument '\' mov edi, 0x0 // address at 0? doesn't make sense call strtok mov qword [rbp-0x48], rax // this is always going to return 0 cmp qword [rbp-0x48], 0x0 jne 0x400d2d // want to jump here, but can't </code></pre>
strtok called on char pointer at 0
|x86|
<p>You should right-click and select "reset pointer type". And then you get "make new struct" in the menu. </p>
23081
2020-01-23T18:04:29.000
<p>I remember that hexrays has the option to generate a dummy struct from a pointer. That is if we access a pointer in offsets 0x36, 0x24 it will create a struct with members off24 , off36. </p> <p>In what cases do I see this option in the menu? Or how to make it appear? I remember that I got it once and it helped me. But since I don't see it , where it is very logical. So, I guess I don't understand its logic. Either this, or it is not present in IDA 7.4 .</p>
Generate dummy struct in IDA hexrays
|struct|
<p>You problem is that your shellcode uses <code>RDX</code> by setting <code>dl</code> to <code>9</code> for the sake of <code>sys_write</code> syscall. You are not setting this variable back to it's initial value of <code>0</code> and unfortunately this is being passed to <code>_start</code> where it's being treated as a pointer to function that will be executed as a finalizer. That's why you're getting a segfault since CPU try to execute code from address <code>0x9</code>.</p> <p>You should save the registers before you execute your shellcode and restore them before returning to the entry point. But for the sake of this example it will work if you would just clear (r)dx before jumping back.</p> <p>Modified shellcode with added <code>\x48\x31\xd2</code> for <code>xor rdx,rdx</code> and changed offsets at <code>shellcode[10]</code> and <code>shellcode[37]</code> to adjust for additional bytes in it (modified them manually - if you have the source code - you can do that in code and compile)</p> <pre><code>unsigned char shellcode[] = "\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\xeb" "\x19\x5e\xb0\x01\x40\xb7\x01\xb2\x09\x0f" "\x05\x48\xb8\x41\x41\x41\x41\x41\x41\x41\xff\x48\x31\xd2" "\xff\xe0\xe8\xe2\xff\xff\xff\x68\x69\x6a" "\x61\x63\x6b\x65\x64\x0a"; </code></pre> <p>A bit more explanation why <code>RDX</code> is problematic here. After your shellcode finishes its job it executes <code>_start</code> which has those two lines as in the beginning:</p> <pre><code> 00400a30 31 ed XOR EBP ,EBP 00400a32 49 89 d1 MOV R9 ,RDX </code></pre> <p>so whatever will be in <code>RDX</code> will be assigned to <code>R9</code>. Later the <code>__libc_start_main</code> is called and if you check its' signature (for example <a href="https://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/baselib---libc-start-main-.html" rel="nofollow noreferrer">here</a>) you can see it takes 7 arguments. The are passed via registers and according to Linux ABI the 6th is passed as a <code>R9</code> register and the 6th parameter in <code>_libc_start_main</code> is callback for finalizers. That's why value in <code>RDX</code> matters as it's being passed to <code>R9</code> and in the end ends up as a callback address.</p>
23083
2020-01-23T23:28:51.507
<p>So after changing the entry point via the <strong>e_entry</strong> field I managed to execute my shellcode before returning control to the original entry point. Here's how I did it:</p> <pre><code> // write string and jump to OEP, patch address at 23 unsigned char shellcode[] = "\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\xeb" "\x16\x5e\xb0\x01\x40\xb7\x01\xb2\x09\x0f" "\x05\x48\xb8\x41\x41\x41\x41\x41\x41\x41" "\xff\xe0\xe8\xe5\xff\xff\xff\x68\x69\x6a" "\x61\x63\x6b\x65\x64\x0a"; </code></pre> <p>So as soon as I parse the ELF header I patch the shellcode:</p> <pre><code>uint64_t oep = ehdr-&gt;e_entry; memcpy(&amp;opcode[23], &amp;oep, 8); </code></pre> <p>Everything works, the shellcode executes and then execution resumes where it should. The problem is that after the target's main function finishes it segfaults(To make things simple I just made a program that prints a string).</p> <p>So I used gdb and IDA to see what's going on. Just to make things clear the flow of excution is as follows:</p> <ul> <li>execution starts at the shellcode</li> <li>shellcode jumps to _start</li> <li>_start calls libc_start_main</li> <li>main executes and returns to libc_start_main</li> </ul> <p>Now, after main returns IDA shows the following:</p> <pre><code>libc_start_main: ext:000000000040244B lea rax, [rsp+108h+var_98] .text:0000000000402450 mov fs:300h, rax .text:0000000000402459 mov rdx, cs:environ .text:0000000000402460 mov edi, [rsp+108h+var_FC] .text:0000000000402464 mov rsi, [rsp+108h+var_F8] .text:0000000000402469 mov rax, [rsp+108h+mainaddr] .text:000000000040246E call rax ; jump to main .text:0000000000402470 mov edi, eax .text:0000000000402472 .text:0000000000402472 loc_402472: ; CODE XREF: __libc_start_main+4AF↓j .text:0000000000402472 call exit .text:0000000000402477 ; ----------------------------------------------------------- </code></pre> <p>The <strong>exit</strong> function ends up calling <strong>run_exit_handlers</strong> which appears to be the real culprit, as it faults with the following instruction:</p> <pre><code>mov rdx, [rax+18h] mov rdi, [rax+20h] mov qword ptr [rax+10h], 0 mov esi, ebp ror rdx, 11h xor rdx, fs:30h call rdx ; faults jmp loc_40823A </code></pre> <p>For some reason rdx has the value of 9, which is not allowed and hence causes the segmentation fault.</p> <p>I searched for information on <strong>run_exit_handlers</strong> but didn't find anything meaningful.</p> <p>So my question is: Why is this happening? All my shellcode does is write a string and jump to the OEP, it shouldn't really affect anything else.</p>
ELF file crashing after executing shellcode
|ida|x86|elf|shellcode|
<p>You need to load the last 64KB of the ROM at linear address 0xF0000 (0xF000:0000) and create there a 16-bit segment with the base 0xF000. Then all your “low addresses” will line up (they point into the current segment with CS=0xF000). </p> <p>In case you get references to E000, load the second 64KB chunk and so on. </p> <p>Once you get to 32-bit code, it will likely be using 32-bit addressing with the end of the ROM at FFFFFFFF, so load and create 32-bit segments accordingly. </p>
23086
2020-01-24T12:10:46.973
<p>I'm trying to reverse a BIOS of an industrial PC in order to repair it. The device is based on an ETX-formfactor mobo, obscure Italian SECO M671, very similar to an old Kontron PM-15(C), but with a custom OEM BIOS. I.e., Intel Celeron M (mobile = Dothan family) processor + 82855 Northbridge + 82801 (ICH4) Southbridge. BIOS is stored on an Intel Firmware Hub-compatible flash chip (sst49lf004b), which is connected to the LPC bus.</p> <p>The mobo started to refuse to POST (blank screen and nothing happens) with POST sequence d0, 00, d1, d2. I don't know why there is 00h code (it usually means that control is handed to the OS) and I tried to ignore it. d0, d1, d2 pattern corresponds to AMIBIOS8, I thought, (and yes, noone remembers the bios manufacturer) and means bad bootblock checksum.</p> <p>Then I've made a dump of the contents of the flash chip with a parallel programmer. But they turned out to be fine, exactly equal to the backup file (taking into account some offset differences)! Actually, except one thing: flash chip contains (far apart from the "main" code section) a second VGA BIOS module which I've not found in the backups. But I suppose it can't hurt that much and it is there probably for some optional functionality.</p> <p>So either a bad LPC controller inside flash chip (because programming interface is parallel, this is still possible), or I've misinterpreted the POSTcodes. Also I've compared my backup file to some AMI update files and found no similarities. So it seems BIOS reversing and understanding D2 is now my only option. Probably once I disassemble it right, I'll just have to search for immediate 0xd2-s and find the right one).</p> <p>I've loaded flash chip image into IDA, looked up chipset datasheet (which, BTW, I found incredibly unclear on the topic of BIOS memory mapping) and corrected flash chip addresses accordingly, i.e. copied upper 128K of BIOS ROM to 0xE0000 to 0xFFFFF 16-bit analysis section, and also copied everything that fits to High-BIOS area FFE0_0000h-FFFF_FFFFh (32-bit analysis section, because of 32-bit address). Then started analysis at 0xFFFF0 (x86 reset vector, 16-bit real mode). Processor setting is P6 (as far as I can tell Dothan family is based on P6 arch) And this is what I get (note that F7A1 and the pointer in red both lead to memory which is not mapped to BIOS ROM, at least as far as I can tell from the datasheet): <a href="https://i.stack.imgur.com/KhNhl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KhNhl.png" alt="IDA disassembly"></a></p> <p>Obviously, 32-bit analysis (at FFFF_FFF0) of the first 16 bytes executed makes no sense too, since the processor starts up in real mode.</p> <p>Keyboard controller access (first check if it's busy, then enable A20 - standard x86 thing) tells me that I was probably right with reset vector memory mapping.</p> <p>But why does it jump to some empty locations? What am I doing wrong? Flash chip image and backup file: <a href="https://drive.google.com/drive/folders/1MwpiqiRK3N9ZBajyiOUuZde522236gmq?usp=sharing" rel="noreferrer">https://drive.google.com/drive/folders/1MwpiqiRK3N9ZBajyiOUuZde522236gmq?usp=sharing</a></p> <hr> <p>EDIT: The pointer in red actually leads to a location mapped to BIOS ROM, my bad. Here is where the control jumps: <a href="https://i.stack.imgur.com/mdGYN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mdGYN.png" alt="IDA disassembly2"></a> We've found POSTcode D0, that's great. But here all jumps lead to some low addresses, which are not mapped to BIOS ROM. Same problem repeats.</p>
BIOS first jump leads to empty memory
|ida|x86|firmware|firmware-analysis|bios|
<p>I did not find anything using the whole message; however, because the last 5 bytes are the same in all the messages you provided, I omitted them one by one and ran reveng on the truncated messages. </p> <p>reveng provides the following output if we leave out the last 4 bytes:</p> <pre><code>./reveng -w 8 -s 301300B9 31130036 321300BA 33130035 width=8 poly=0x1d init=0xff refin=false refout=false xorout=0xff check=0x4b residue=0xc4 name="CRC-8/SAE-J1850" </code></pre> <p>This algorithm works for all of the samples you provided. </p>
23094
2020-01-24T23:52:33.347
<p>Maybe someone can help me with algorithm for checksum calculation. CRC 8 does not fit. Left byte is CRC.</p> <pre><code>B9 30 13 00 00 20 00 00 36 31 13 00 00 20 00 00 BA 32 13 00 00 20 00 00 35 33 13 00 00 20 00 00 BF 34 13 00 00 20 00 00 30 35 13 00 00 20 00 00 BC 36 13 00 00 20 00 00 33 37 13 00 00 20 00 00 B5 38 13 00 00 20 00 00 3A 39 13 00 00 20 00 00 B6 3A 13 00 00 20 00 00 39 3B 13 00 00 20 00 00 B3 3C 13 00 00 20 00 00 3C 3D 13 00 00 20 00 00 B0 3E 13 00 00 20 00 00 3F 3F 13 00 00 20 00 00 7E 01 00 00 00 20 00 00 F2 02 00 00 00 20 00 00 7D 03 00 00 00 20 00 00 F7 04 00 00 00 20 00 00 78 05 00 00 00 20 00 00 F4 06 00 00 00 20 00 00 7B 07 00 00 00 20 00 00 FD 08 00 00 00 20 00 00 72 09 00 00 00 20 00 00 FE 0A 00 00 00 20 00 00 71 0B 00 00 00 20 00 00 FB 0C 00 00 00 20 00 00 74 0D 00 00 00 20 00 00 F8 0E 00 00 00 20 00 00 77 0F 00 00 00 20 00 00 F1 00 00 00 00 20 00 00 </code></pre>
CAN Bus checksum
|crc|
<p>Well thanks to @IgorSkochinsky's suggestion, I found a disassembler for the Blackfin architecture in the <a href="https://hub.docker.com/r/pf0camino/cross-bfin-elf" rel="noreferrer">pf0camino/cross-bfin-elf</a> Docker image. Being in Docker meant it was easy to run and I didn't have to mess around with installing cross compilers myself. I was then able to disassemble the image with this command:</p> <pre><code>bfin-elf-objdump -D -b binary -mbfin bootloader.bin &gt; bootloader.disasm </code></pre> <p>This produced a large text file, which took some time to go through since the output didn't have any sort of automatic recognition applied to it. Nevertheless, after reading up on Blackfin assembler and searching for various known constants, I was able to work out what the code was doing.</p> <p>Eventually I found the decryption function, and converted it to Javascript for use in my project. It came out like this:</p> <pre><code>function decodeBlock(baseBlockNum, data) { // If the block is zero, the function won't change the data, so this magic // number is used. Block 0 is part of the bootloader, which never appears // to be reflashed in official firmware images. let key = baseBlockNum || 0x545A; for (let pos = 0; pos &lt; data.length;) { // Let's be fancy and execute the `if` statement without using an `if`. //if (key &amp; 1) key ^= 0x8005; key ^= ( ((key &amp; 1) &lt;&lt; 15) | ((key &amp; 1) &lt;&lt; 2) | (key &amp; 1) ); // This rotate operation is a bit redundant, because the above XOR // always clears the lower bit. So let's skip that part. //key = ((key &amp; 1) &lt;&lt; 15) | (key &gt;&gt; 1); key &gt;&gt;= 1; data[pos++] ^= key &amp; 0xFF; data[pos++] ^= key &gt;&gt; 8; } } </code></pre> <p>The <code>baseBlockNum</code> parameter is the ROM address for the block, in units of 0x1000 bytes. So for a block to be flashed at address 0x4000, the parameter is 4.</p> <p>I've tested this on the full firmware file and it decrypts it successfully!</p>
23098
2020-01-25T10:08:40.040
<h3>TL;DR</h3> <p>I have an encrypted image and the cleartext version, and I'm almost certain it's an XOR cipher, but I can't figure out how to decrypt it. I have a few clues listed below.</p> <ul> <li><a href="http://files.shikadi.net/malv/files/stackexchange/ciphertext.bin" rel="nofollow noreferrer">Ciphertext excerpt</a> (20kB)</li> <li><a href="http://files.shikadi.net/malv/files/stackexchange/cleartext.bin" rel="nofollow noreferrer">Cleartext excerpt</a> (20kB)</li> </ul> <h3>Detail</h3> <p>I'm trying to reverse engineer the firmware for a pro audio device, and I've got most of the way but I'm stuck on a step in the middle.</p> <p>I'm pretty sure it's an XOR cipher (as there was one XOR decryption already to get to this point, and there is another one after). It seems to be applied in blocks of 0x1000 bytes, as the key seems to reset after this many bytes. The initial key seems to be <code>2</code> and it is incremented by 1 every 0x2000 bytes. At the start of each block, the current 'initial key' is XOR'd with <code>0x4002</code> to produce the real key. Thus the keys reset to these values at these offsets:</p> <pre><code>Offset | Key -------+-------------------- 0x0000 | 2 ^ 0x4002 = 0x4000 0x1000 | 2 ^ 0x4002 = 0x4000 0x2000 | 3 ^ 0x4002 = 0x4001 0x3000 | 3 ^ 0x4002 = 0x4001 0x4000 | 4 ^ 0x4002 = 0x4006 </code></pre> <p>The cipher seems to work in units/words of 16-bits, little endian. After each word has been XOR'd with the key, the key is bit-shifted right by <code>1</code>.</p> <p>However this is where I have come unstuck. Sometimes, apparently at random, the key needs to be XOR'd by <code>0x4002</code>. I cannot see the pattern as to when this happens. Initially it looks like it happens every four bytes (two words) but this falls apart at offset 0x22.</p> <p>I tried XOR'ing the ciphertext and cleartext to produce a long XOR keyfile, and then tried to work out how to reproduce that keyfile. By XOR'ing my guess against the large keyfile, it should end up as <code>0x00</code> bytes if I am correct. However it often ends up as <code>0x02 0x40</code> bytes, and by writing code that detected these mistakes and adjusted the key accordingly, I was able to see where and when the key needs to be XOR'd by <code>0x4002</code> in order to decrypt the data correctly. I've been staring at it for a few hours now, but it just looks random to me, I can't spot any pattern!</p> <p>For example, in the block starting at offset 0, the key needs to be XOR'd with <code>0x4002</code> at offsets 0, 4, 8, 12 (every four bytes) but then at offset 20 it drops back to every two bytes (20, 22, 24, -not 26-, 28, 2A, 2A, -not 2E-, etc.) I can't see the pattern as to when this extra XOR on the key should happen. It doesn't seem to be related to the previous value, the offset, the key value, etc. (of course it probably is I just can't see it.)</p> <h3>Background</h3> <p>The source data has come from a firmware file from the manufacturer, which I have decoded from MIDI SysEx events and decrypted with an XOR cipher. I know this cipher is correct as it produces a correct header and footer, along with block numbers every 256 bytes. After processing these I end up with a source image that is exactly the same size as the firmware dump taken direct from the device's ROM chip with a Minipro EEPROM reader.</p> <p>The XOR cipher I am struggling with is the last step in going from the manufacturer's firmware file to what gets flashed into the ROM chip (and vice versa, as programming a custom ROM is my ultimate goal).</p> <p>Note that what does get flashed into the ROM chip (what I am referring to here as the cleartext) is itself further XOR encrypted, however I have successfully decrypted that so it is no issue here (and this in-flash encryption is required as the bootloader expects it.)</p> <p>If anyone is able to assist me in figuring out this algorithm, I will be implementing it and releasing it as open source, as <a href="https://github.com/Malvineous/behringerctl" rel="nofollow noreferrer">part of a project I am working on</a>.</p> <h3>Disassembly</h3> <p>Further to the question from @Igor Skochinsky, I haven't yet tried to disassemble the bootloader as I'm not sure how to go about it. Here's the <a href="http://files.shikadi.net/malv/files/stackexchange/deq2496-bootloader.bin" rel="nofollow noreferrer">bootloader code</a>, which may contain a 10-byte header according to the <a href="https://www.analog.com/media/en/technical-documentation/data-sheets/ADSP-BF531_BF532_BF533.pdf" rel="nofollow noreferrer">Blackfin ADSP-BF531 datasheet</a>.</p> <p>To avoid confusion if anyone is able to disassemble the code, the XOR encryption I am asking about is only applied during the flash ROM programming stage. A block of data comes in as 7-bit data via the MIDI port (function number 0x34 "write flash block"), is decoded into 8-bit data, an unrelated XOR decrypt with the key <code>TZ'04</code> is applied (the key is loaded from offset 0x2C84), the CRC is checked, the three-byte header is stripped and the remaining 256-byte block is (presumably) stored in RAM.</p> <p>The manual says the device only acknowledges the write after the 16th 256-byte block, which is 4 kB of data. The XOR algorithm in question resets the key every 4 kB, so it would appear that the device collects the 256-byte blocks until it reaches 4 kB and applies the unknown XOR cipher at that point, after which it writes the resulting cleartext onto the flash chip (which is an SST39SF040, identified as chip ID 0xBFB7).</p> <p>Unrelated to this (but to help guide any disassembly), the bootloader also loads data from the flash chip during a normal boot and then XOR decodes it with an 'application key'. This runtime XOR is solved as follows:</p> <ol> <li>Bootloader XOR key loaded from offset 0x3002, length 0x38.</li> <li>Bootloader ciphertext read from offset 0x303A, length 0x38.</li> <li>Bootloader XOR and ciphertext applied to produce the 'application key'.</li> <li>Flash memory is read from offset 0x4000, application key used for XOR, result stored in memory ready to execute.</li> </ol>
Stuck on XOR decryption of firmware
|firmware|decryption|xor|
<p>Well thanks to @IgorSkochinsky who suggested in another question of mine to try a disassembler, I found a <a href="https://hub.docker.com/r/pf0camino/cross-bfin-elf" rel="nofollow noreferrer">Docker image that contained a Blackfin toolchain</a> which allowed me to use <code>objdump</code> to disassemble the code:</p> <pre><code>bfin-elf-objdump -D -b binary -mbfin bootloader.bin &gt; bootloader.disasm </code></pre> <p>After hastily consulting a manual on Blackfin assembler and poking around a bit, I was able to get a vague idea of what was going on, and I was able to find the CRC function, which turned out not to be a CRC function at all, but a DIY checksum.</p> <p>Using the disassembly as a reference, I was able to replicate the algorithm in my Javascript code:</p> <pre><code>function behringer_crc8(data) { let crc = 0; for (let b of data) { for (let j = 0; j &lt; 8; j++) { if (!((b ^ crc) &amp; 1)) crc ^= 0x19; b &gt;&gt;= 1; // Rotate (shift right, move lost LSB to new MSB) crc = ((crc &amp; 1) &lt;&lt; 7) | (crc &gt;&gt; 1); } } return crc ^ 0xbf; } </code></pre> <p>Comparing this code against the distributed firmware update shows that it is able to reproduce the CRC bytes correctly!</p> <p>It also turned out that despite the manual saying the two-byte block number prefix was included in the checksum, it turned out it wasn't, and only the 256-byte content is checksummed.</p>
23099
2020-01-25T10:58:00.530
<p>The Behringer DEQ2496 audio device can have commands sent to it via MIDI, however they require a valid CRC code in order for the device to accept them.</p> <p>I have thus far been unable to work out how the CRC code is calculated. The manual suggests it is CRC8 however I have not been able to configure a CRC8 algorithm to produce matching values.</p> <p>Here is some sample data, including valid CRC codes:</p> <ul> <li><a href="http://files.shikadi.net/malv/files/stackexchange/block-40.bin" rel="nofollow noreferrer">Block 0x0040</a></li> <li><a href="http://files.shikadi.net/malv/files/stackexchange/block-41.bin" rel="nofollow noreferrer">Block 0x0041</a></li> <li><a href="http://files.shikadi.net/malv/files/stackexchange/block-41.bin" rel="nofollow noreferrer">Block 0x0042</a></li> <li><a href="http://files.shikadi.net/malv/files/stackexchange/block-42.bin" rel="nofollow noreferrer">Block 0x0043</a></li> <li><a href="http://files.shikadi.net/malv/files/stackexchange/block-43.bin" rel="nofollow noreferrer">Block 0x0043</a></li> <li><a href="http://files.shikadi.net/malv/files/stackexchange/block-ff00.bin" rel="nofollow noreferrer">Block 0xFF00</a></li> </ul> <p>The DEQ2496 SysEx manual says of the layout of each of the above files:</p> <blockquote> <p><strong>blockdata</strong>: 7/8 coded: blockno_h, blockno_l, crc, data[256].</p> <p><strong>crc</strong>: crc8 checksum of blockno_h, blockno_l, data[256]</p> <p><strong>blockno</strong>: transferred 256 byte data block number (bits 21..15, 14..8 of flash offset); blocks 0-0x1f: boot loader; blocks 0x20..0x5ef: application; blocks 0x5f0-0x5ff: startup screen; blocks 0x600-0x67f: presets; blocks 0x680-0x69f: temporary buffers; blocks 0x6a0-0x7ff: hw configuration; block no 0xff00 shows text message data[0..52] on screen</p> <p><strong>data</strong>: data block</p> </blockquote> <p>I have taken care of the 7/8 coding, so now I have a block of 3+256 bytes, consisting of:</p> <ul> <li>Offset 0: 16-bit big endian integer, block number</li> <li>Offset 2: 8-bit integer, CRC (this is the value I am trying to calculate)</li> <li>Offset 3+: Actual data</li> </ul> <p>I've tried a couple of CRC algorithms (with and without a lookup table), written code to run through all possible 8-bit polynomials, initial and final XOR values, and yet I can't find any parameters that work for more than one block.</p> <p>Although the manual suggests the CRC byte itself is not included in the CRC calculation, I also tried leaving it in place and setting it to various values like <code>0x00</code> and <code>0xFF</code> however this didn't yield any results either.</p> <p>Is there anyone with more CRC knowledge than me who is able to figure out what they mean here by &quot;crc8 checksum&quot;?</p>
Behringer CRC8 algorithm
|crc|
<p>I'm write keygen random: <code>keygen('ALVMGRCTQQEYMNAHDANKPGKPO')</code></p> <p><a href="https://i.stack.imgur.com/wSLNc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wSLNc.png" alt="run"></a></p> <pre><code>GSFLOWZJOEWPOQFXFHVASFTPNBNTEJ -&gt; G060?9@@7&gt;684A8&lt;712&lt;2=&lt;0A8A::8 060?9@@7&gt;68 4A8&lt;712&lt;2=&lt; 0A8A::8 01949999431597 030156882999840 43256662 (length 14 + 15 + 8 = 37) </code></pre> <p><strong>0194999943159703015688299984043256662</strong> this satisfy with <strong>0194x999xxxxxx03015688xxxxx404325666x</strong> :D</p> <pre><code>// example keygen('ALVMGRCTQQEYMNAHDANKPGKPO') // source function keygen(code) { let indexes = [ [3, 4, 28, 29, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 5, 17, 18, 19, 20, 21, 22], [3, 4, 1, 2, 29, 30, 15, 16, 31, 32, 33, 34, 35, 36, 28, 17, 18, 19, 20, 21, 22] ] code = encodeString(code) let num = encodeNumber(code.substr(1, 12)).toString().padStart(15,0)+encodeNumber(code.substr(13, 12)).toString().padStart(15,0) let key = [...Array(37)].map((e,i)=&gt;[5,6,7].indexOf(i) &gt;= 0 ? '9' : Math.floor(Math.random()*10).toString()) indexes[0].forEach((e,i)=&gt;key[indexes[1][i]-1]=num[e-1]), key = key.join('') let result = decodeNumber(key.substr(0, 14)).padStart(11,0)+decodeNumber(key.substr(14, 15)).padStart(11,0)+decodeNumber(key.substr(29, 8)).padStart(7,0) return decodeString(sum(result,0)+result) } var alphabet = `SDHACENOIFKXQLBMPJTZURWVGY` function encodeString(s) { let result = s.charAt(0), idx = alphabet.indexOf(s.charAt(0)) for (let i=0; i&lt;s.length-1; i++) { result += String.fromCharCode((alphabet.indexOf(s.charAt(i + 1))-idx-i+284)%26+48) idx = alphabet.indexOf(s.charAt(i + 1)) } return result } function decodeString(s) { let result = s.charAt(0), idx = alphabet.indexOf(s.charAt(0)) for (let i=0; i&lt;s.length-1; i++) { let num = (s.charCodeAt(i + 1) - 48) idx = [...alphabet].findIndex((x,y) =&gt; (y-idx-i+284)%26 == num) result += alphabet[idx] } return result } function encodeNumber(s) { let n = 0, l = 1 for (let i=s.length; i&gt;0; i--) { let c = (s.charCodeAt(i-1)-48)*l n += c, l *= 19 } return n } function decodeNumber(n) { let c = 0, s = [] for (let i=0; c != n; i++) { let v = (n % 19**(i+1)) s.push((v-c)/19**i+48) c = v } return String.fromCharCode.apply(null, s.reverse()) } function sum(s, idx = 1) { let cs = 0 for (; idx &lt; s.length; idx++) cs+=s.charCodeAt(idx) return alphabet[cs%25] } </code></pre>
23101
2020-01-25T15:48:37.180
<p>So I have an ancient application for a company that has since gone bust and I thought I'd look at how it works; it provides a key, and requires a key given to it. Both these keys are encoded in a certain way and then parts of the encoded value are compared for equality. Firstly I'll explain the encoding process as I have remade it in javascript</p> <p>This appears to be a caesar cipher in some shape or form and I'm pretty sure it equates to the formula: <code>C(x) = (P(b - a - x + 284) mod 26) + 48</code> where<br> x = character number<br> b = current characters index in alphabet<br> a = previous letters index in alphabet</p> <pre><code>const alphabet = `SDHACENOIFKXQLBMPJTZURWVGY` function encodeString(s) { var result = s.charAt(0), lastLetterIdx = alphabet.indexOf(s.charAt(0)) for(let i = 0; i &lt; s.length - 1; i++) { let thisLetterIdx = alphabet.indexOf(s.charAt(i + 1)) let cypherNum = thisLetterIdx - lastLetterIdx - i cypherNum += 284 let modNum = cypherNum % 26 let encChar = String.fromCharCode(modNum + 48) result += encChar lastLetterIdx = thisLetterIdx } return result } </code></pre> <p>A key provided by the software is<br> <code>ALVMGRCTQQEYMNAHDANKPGKPO</code><br> which gets encoded to<br> <code>A87&gt;4A26;@8833898:::;&lt;?8B</code></p> <p>The code is then checksumed by skipping the first character and adding the ascii values up, so in this case that number is 1378, mod 25 = 3 and the alphabet character at position 3 (0 indexed) is <code>A</code> which matches the first character of the key.</p> <p>For encoding step 2 the software takes characters 1-12 (87>4A26;@883) and encodes it into a number via the following:</p> <pre><code>function encodedStringToNumber(str) { var number = 0, letterMulti = 1 for(let i = str.length; i &gt; 0; i--) { if(i &lt; str.length) letterMulti = letterMulti * 19 let letter = str.charCodeAt(i-1) letter -= 48 letter *= letterMulti number += letter } return number } </code></pre> <p>It then converts the number to a string and pads left with <code>0</code> to ensure its 15 characters long, after doing that with both half's it string concats the numbers to get a result of<br> <code>979440403325666401568800000018</code></p> <p>If we do the same thing with a random test key I made of <code>VABCDEFGHIJKLMNOPQRSTUVWXYZABK</code><br> we get an encrypted key of<br> <code>V48&lt;BHG7EFH7@&gt;2;B4@;G661@&gt;C88B</code><br> that gets checksumd as before and then gets converted to a string with 11 characters from index 1, 11 characters from index 12 and 7 characters from index 23, so:</p> <pre><code>48&lt;BHG7EFH7 @&gt;2;B4@;G66 1@&gt;C88B </code></pre> <p>We convert them to numbers then ensure string lengths of 14, 14 and 7 by padding the left with <code>0</code> again. So a result of<br> <code>2732684617734210265934650819588621338</code></p> <p>We now split this number and the number provided in the software down to some key elements and compare the values.</p> <p>Lets say key A is the software provided key of <code>979440403325666401568800000018</code> and key B is the key I'm randomly using of <code>2732684617734210265934650819588621338</code></p> <p>From key A take characters (indexes are 1 based here): </p> <pre><code>3-4 (94) 28-29 (01) 6-7 (04) 8-9 (03) 10-15 (325666) 5 (4) 17-22 (015688) </code></pre> <p>From key B take:</p> <pre><code>3-4 (32) 1-2 (27) 29-30 (58) 15-16 (10) 31-36 (862133) 28 (9) 17-22 (265934) </code></pre> <p>Those values need to be the same and as an added check key B 6-8 needs to be "999" (i think this is an install flag and 000 is an uninstall flag)</p> <p>So with the key given by application I know I need to make a key that encrypts to the following number (where X can be anything):<br> <code>0194x999xxxxxx03015688xxxxx404325666x</code></p> <p>This number needs to satisfy the comparisons, have the 999 in the correct place and when encoded as letters needs to validate the checksum mentioned earlier along with each letter of the encoded value being >= '0', by that I mean the ascii value is at or above 48.</p> <p>The problem I have is given the way it encrypts the key I can't for the life of me work out how they could make a program which does the reverse, the first step seems easy if I knew how to do modular arithmetic, but converting a number to letters is straight up beyond me. </p>
Reversing an encoded key with a given cipher - figuring out the reverse algorithm
|decryption|
<p>Most RTOS code is usually a single monolithic binary and is not split into separate binaries like a high-level OS. Usually there is some startup code, some library routines and user-provided code in forms of <em>tasks</em> which are nothing more than simple functions performing the necessary work in a simple infinite loop. The “main function” called by the RTOS startup would register the tasks, set up the shared resources like timers, queues, semaphores etc. and invoke the RTOS entry point which starts dispatching the tasks, switching between them periodically so that each gets a chance to run. </p> <p>While there is no file system, there may be other useful information in the binary. Most RTOSes allow you to give names to tasks so you may be able to find some strings and from the references discover task creation/registration functions. Sometimes a table of structures is used(e.g. a pointer with name and pointer to the task function). </p> <p>To force disassembly of a big chunk of code in IDA you can use selection, e.g.:</p> <ol> <li>Go to the potential start of code (e.g. beginning of the code segment)</li> <li>Drop selection anchor (Alt-L)</li> <li>Go to the end of code (e.g. by clicking in the navigation bar, scroll bar or via keyboard) do that the whole chunk is selected. </li> <li>Press C and pick Analyze or Force (you may need to experiment and see which one works better)</li> </ol> <p>Note that in some cases data may also be interpreted as valid instructions, so you might get false positives (especially with the “force” option), which may require you to fix things up afterwards. But this should help you get started and discover some valid code. </p>
23104
2020-01-25T19:56:41.330
<p>I am reverse engineering a firmware which has a Linux and an RTOS component. I used binwalk to easily locate the Linux filesystems, extract them, mount them, and now I have binaries which I can open in IDA Pro and continue working on.</p> <p>However, I am having a <em>much more difficult time</em> doing this with the RTOS side of the firmware. In my target firmware image, I was able to identify that the RTOS sits <em>above</em> the Linux filesystems in memory address, by performing some string searches for common RTOS-related things. The code is definitely ARM, likely 32 bit, little-endian. This is a Cortex-A7. I saw artifacts which indiciate that it is also likely an ITRON RTOS or perhaps FreeRTOS. But essentially, binwalk extracted 3-4 chunks of "data" files which contain all of this. So I am able to get some useful info from looking at string offsets in these chunks. Seeing as most of the data appear to be strings and ARM instructions, I've opened them in IDA Pro. IDA Takes A LONG TIME to parse, but once they're parsed, everything is just data and needs to be manually turned into code. This is where I'm hung-up. I have 2 main questions:</p> <ol> <li>Does an RTOS system like this have a proper "file system" that I could "mount" to view the binaries like I did with the Linux ext and squashfs ones? All filesystems I've ever worked with using binwalk have been Linux ones. What are common RTOS file systems if this is the case?</li> <li>If not, how can I go about viewing the ARM disassembly of these chunks in a legible way using IDA Pro?</li> </ol>
How to make sense of RTOS in firmware?
|ida|firmware|file-format|firmware-analysis|operating-systems|
<p>At a guess, <code>lpParameter</code> is located in a segment marked read-only (e.g. a code section), so the decompiler considers its value to be constant (probably zero) which is why all subsequent accesses are also zero-based. There are two solutions:</p> <ol> <li><p>Mark the segment containing <code>lpParameter</code> to be writable (edit segment properties). In case the writable data is a small part of the otherwise read-only segment, creating a new segment just for data is a good idea</p></li> <li><p>Mark only <code>lpParameter</code> as writable by adding <code>volatile</code> specifier to its type definition (use the <kbd>Y</kbd> key). In a similar manner, an otherwise writable variable can be marked as constant by adding a <code>const</code> specifier.</p></li> </ol> <p>Reference: <a href="https://www.hex-rays.com/products/decompiler/manual/tricks.shtml" rel="nofollow noreferrer">Volatile and Constant memory</a>.</p>
23117
2020-01-27T04:11:54.207
<p>I'm trying to analyze a binary that I unpacked, rebuilt, and dumped, using Scylla. After loading it into IDA and viewing pseudocode, I can see that there are errors where IDA tells me that it notices writes to constant memory addresses. After some searching online, I find that this seems quite common, but I haven't really come across a solution for fixing it, and I've just tried to ignore it up to now.</p> <p><a href="https://i.stack.imgur.com/IAwoR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IAwoR.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/32Agt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/32Agt.png" alt="enter image description here"></a></p> <p>At first, I tried to just change all my segments to have write access, but that didn't seem to change anything. <code>0x007F944F</code> is the first memory error.</p> <p>Would anyone mind telling me how I go about to solve this? Thank you.</p> <p>EDIT: Here is the entire disassembly of that function:</p> <pre><code>.MPRESS1:007F93F2 align 10h .MPRESS1:007F9400 .MPRESS1:007F9400 ; =============== S U B R O U T I N E ======================================= .MPRESS1:007F9400 .MPRESS1:007F9400 ; Attributes: bp-based frame .MPRESS1:007F9400 .MPRESS1:007F9400 sub_7F9400 proc near ; CODE XREF: Stool__ctor+6F↑p .MPRESS1:007F9400 ; Stool__ctor+91↑p ... .MPRESS1:007F9400 .MPRESS1:007F9400 a3 = dword ptr 8 .MPRESS1:007F9400 u0 = dword ptr 0Ch .MPRESS1:007F9400 .MPRESS1:007F9400 000 push ebp .MPRESS1:007F9401 004 mov ebp, esp .MPRESS1:007F9403 004 cmp ds:lpParameter, 0 .MPRESS1:007F940A 004 jz short loc_7F9410 .MPRESS1:007F940C 004 xor eax, eax .MPRESS1:007F940E 004 pop ebp .MPRESS1:007F940F 000 retn .MPRESS1:007F9410 ; --------------------------------------------------------------------------- .MPRESS1:007F9410 .MPRESS1:007F9410 loc_7F9410: ; CODE XREF: sub_7F9400+A↑j .MPRESS1:007F9410 004 push esi ; a2 .MPRESS1:007F9411 008 push offset sub_7F49C0 ; lpTopLevelExceptionFilter .MPRESS1:007F9416 00C call ds:SetUnhandledExceptionFilter .MPRESS1:007F941C 008 push 3DA4h ; size_t .MPRESS1:007F9421 00C mov esi, eax ; a2 .MPRESS1:007F9423 00C call ??2@YAPAXI@Z ; operator new(uint) .MPRESS1:007F9428 00C add esp, 4 .MPRESS1:007F942B 008 test eax, eax .MPRESS1:007F942D 008 jz short loc_7F9438 .MPRESS1:007F942F 008 mov ecx, eax .MPRESS1:007F9431 008 call StoolGuard__ctor .MPRESS1:007F9436 008 jmp short loc_7F943A .MPRESS1:007F9438 ; --------------------------------------------------------------------------- .MPRESS1:007F9438 .MPRESS1:007F9438 loc_7F9438: ; CODE XREF: sub_7F9400+2D↑j .MPRESS1:007F9438 008 xor eax, eax .MPRESS1:007F943A .MPRESS1:007F943A loc_7F943A: ; CODE XREF: sub_7F9400+36↑j .MPRESS1:007F943A 008 push [ebp+a3] ; a2 .MPRESS1:007F943D 00C mov ecx, eax ; a1 .MPRESS1:007F943F 00C mov ds:lpParameter, eax .MPRESS1:007F9444 00C call sub_7F6610 .MPRESS1:007F9449 008 mov ecx, ds:lpParameter .MPRESS1:007F944F 008 mov [ecx+10h], eax .MPRESS1:007F9452 008 cmp eax, 755h .MPRESS1:007F9457 008 jz short loc_7F9460 .MPRESS1:007F9459 008 call sub_7F4B00 .MPRESS1:007F945E 008 jmp short loc_7F9476 .MPRESS1:007F9460 ; --------------------------------------------------------------------------- .MPRESS1:007F9460 .MPRESS1:007F9460 loc_7F9460: ; CODE XREF: sub_7F9400+57↑j .MPRESS1:007F9460 008 cmp ds:byte_8EB238, 0 .MPRESS1:007F9467 008 jz short loc_7F9476 .MPRESS1:007F9469 008 push offset byte_8EB238 ; lpString .MPRESS1:007F946E 00C call SToolGameGuard__Nop3 .MPRESS1:007F9473 00C add esp, 4 .MPRESS1:007F9476 .MPRESS1:007F9476 loc_7F9476: ; CODE XREF: sub_7F9400+5E↑j .MPRESS1:007F9476 ; sub_7F9400+67↑j .MPRESS1:007F9476 008 mov eax, ds:lpParameter .MPRESS1:007F947B 008 mov eax, [eax+18h] .MPRESS1:007F947E 008 test eax, eax .MPRESS1:007F9480 008 jz short loc_7F9489 .MPRESS1:007F9482 008 push eax ; hEvent .MPRESS1:007F9483 00C call ds:SetEvent .MPRESS1:007F9489 .MPRESS1:007F9489 loc_7F9489: ; CODE XREF: sub_7F9400+80↑j .MPRESS1:007F9489 008 mov eax, ds:lpParameter .MPRESS1:007F948E 008 mov eax, [eax+1Ch] .MPRESS1:007F9491 008 test eax, eax .MPRESS1:007F9493 008 jz short loc_7F949E .MPRESS1:007F9495 008 push 0 ; uExitCode .MPRESS1:007F9497 00C push eax ; hProcess .MPRESS1:007F9498 010 call ds:TerminateProcess .MPRESS1:007F949E .MPRESS1:007F949E loc_7F949E: ; CODE XREF: sub_7F9400+93↑j .MPRESS1:007F949E 008 test esi, esi .MPRESS1:007F94A0 008 jz short loc_7F94A9 .MPRESS1:007F94A2 008 push esi ; lpTopLevelExceptionFilter .MPRESS1:007F94A3 00C call ds:SetUnhandledExceptionFilter .MPRESS1:007F94A9 .MPRESS1:007F94A9 loc_7F94A9: ; CODE XREF: sub_7F9400+A0↑j .MPRESS1:007F94A9 008 mov eax, ds:lpParameter .MPRESS1:007F94AE 008 pop esi .MPRESS1:007F94AF 004 mov eax, [eax+10h] .MPRESS1:007F94B2 004 pop ebp .MPRESS1:007F94B3 000 retn .MPRESS1:007F94B3 sub_7F9400 endp .MPRESS1:007F94B3 .MPRESS1:007F94B3 ; --------------------------------------------------------------------------- </code></pre>
IDA - How to resolve "Write access to const memory detected" error?
|ida|decompilation|error|
<p><strong>SOLUTION</strong></p> <p>I got help from a guy named Peter. He gave me a piece of test code in C. The CRC algorithm looked pretty similar to the ones I already tried. But what was important was that he pointed out that the first sample message most likely had a bit error.</p> <pre><code>#include &lt;stdio.h&gt; int crc16(unsigned char *ptr, int count) { unsigned int crc; char i; crc = 0x0000; while (--count &gt;= 0) { crc = crc ^ (unsigned int) *ptr++; i = 8; do { if (crc &amp; 0x0001) crc = (crc &gt;&gt; 1) ^ 0xA001; /* 0x8005 bit reversed */ else crc = (crc &gt;&gt; 1); } while(--i); } return (crc); } void main() { /* 32 01 6C D9 02 40 40 40 70 03 26 88 */ unsigned char data1[] = {0x6c, 0xd9, 0x02, 0x40, 0x40, 0x40, 0x50, 0x03}; /* 32 01 6C D9 02 40 C8 40 50 03 0D 28 */ unsigned char data2[] = {0x6c, 0xd9, 0x02, 0x40, 0xc8, 0x40, 0x50, 0x03}; printf("crc sent: 8826 computed: %4.4x\n", crc16(data1, sizeof(data1))); printf("crc sent: 280d computed: %4.4x\n", crc16(data2, sizeof(data2))); return; } </code></pre> <p>And when testing the first corrected message and the second message using crc reveng it finds the algorithm</p> <pre><code>$ ./reveng -w 16 -s 6cd90240c84050030d28 ./reveng: warning: you have only given 1 sample ./reveng: warning: to reduce false positives, give 4 or more samples width=16 poly=0x8005 init=0x0000 refin=true refout=true xorout=0x0000 check=0xbb3d residue=0x0000 name="CRC-16/ARC" MattisMacBook:reveng-2.1.0 mattis$ ./reveng -w 16 -s 6CD90240404070032688 ./reveng: warning: you have only given 1 sample ./reveng: warning: to reduce false positives, give 4 or more samples ./reveng: no models found $ ./reveng -w 16 -s 6CD90240404050032688 ./reveng: warning: you have only given 1 sample ./reveng: warning: to reduce false positives, give 4 or more samples width=16 poly=0x8005 init=0x0000 refin=true refout=true xorout=0x0000 check=0xbb3d residue=0x0000 name="CRC-16/ARC" </code></pre> <p>Then I tried getting crc reveng to do the same calculation as the code Peter provided above. It took a while to get the options right. For some reason I had to specify the polynom in the reverse bit order to make it work.</p> <pre><code>$ ./reveng -w 16 -P a001 -i 0000 -x 0000 -l -d width=16 poly=0x8005 init=0x0000 refin=true refout=true xorout=0x0000 check=0xbb3d residue=0x0000 name=(none) $ ./reveng -w 16 -P a001 -i 0000 -x 0000 -l -c 6CD9024040405003 2688 </code></pre> <p><strong>Conclusion and lessons learnt</strong></p> <p>I never thought there could be errors in received data. That was stupid. It is not maybe likely on 9600 bps connection but can happen. Then I was too focused on testing both messages at the same time and never saw that the second message actually returned OK CRC, although it had the bytes swapped.</p> <p>So lessons for myself is: </p> <ol> <li>Have more samples so that transmission errors can be spotted more easily </li> <li>Don't assume that all messages are correct.</li> <li>crc reveng has many options that at first sight can be hard to get right - keep trying!</li> </ol> <p>Thanks to everyone that has helped!</p>
23123
2020-01-27T10:21:47.367
<p>I am trying to connect to an old piece of communication controller which use the IBM BSC synchronous protocol but I have problems to get the CRC right.</p> <p><strong>Background</strong></p> <p>The protocol itself is described quite well in this document: </p> <p><a href="http://bitsavers.trailing-edge.com/pdf/ibm/datacomm/GA27-3004-2_General_Information_Binary_Synchronous_Communications_Oct70.pdf" rel="nofollow noreferrer">http://bitsavers.trailing-edge.com/pdf/ibm/datacomm/GA27-3004-2_General_Information_Binary_Synchronous_Communications_Oct70.pdf</a></p> <p>The sending communication processor is using the Motorola MC6852 chip. But the chip doesn't have hardware crc circuitry so there are software inside the comm. processor that does crc.</p> <p>The actual communication controller is described here: <a href="http://storage.datormuseum.se/u/96935524/Datormusuem/Alfaskop/Alfaskop_System_41_Reference_Manual_IBM3270_Emulation.pdf" rel="nofollow noreferrer">http://storage.datormuseum.se/u/96935524/Datormusuem/Alfaskop/Alfaskop_System_41_Reference_Manual_IBM3270_Emulation.pdf</a></p> <p>Page 89 and onwards describes its use of BSC.</p> <p>Then since this piece of equipment is IBM 3274 model C compatible this manual is applicable: <a href="http://bitsavers.informatik.uni-stuttgart.de/pdf/ibm/3274/GA23-0061-1_3274_Control_Unit_Description_and_Programmers_Guide_Jan84.pdf" rel="nofollow noreferrer">http://bitsavers.informatik.uni-stuttgart.de/pdf/ibm/3274/GA23-0061-1_3274_Control_Unit_Description_and_Programmers_Guide_Jan84.pdf</a></p> <p>Page 159 and onwards has essentially the same information as the other document.</p> <p><strong>Actual Messages</strong></p> <p>I have captured two messages sent by actual communication processor. Please note that the messages are coded in EBCDIC and not ASCII. These are responses to a POLL message. Page 172 and 175 in the IBM document above:</p> <p>32 01 6C D9 02 40 40 40 70 03 26 88 and 32 01 6C D9 02 40 C8 40 50 03 0D 28</p> <p>From my reading of the IBM document the CRC algorithm will reset when it sees a 01 (SOH) or 02 (STX) and then accumulate until it sees a 03 (ETX). A SOH followed by a STX will not reset CRC again at the STX, though. Essentially this means that the CRC bytes in the messages above are the 2688 and 0D28. There is a leading SYN (32) but that is not included in the CRC calculation since it is before the SOH character. The message used for CRC calculation is then: 6C D9 02 40 40 40 70 03 and 6C D9 02 40 C8 40 50 03 respectively. The SOH is not part of the calculation, however the trailing ETX just before the CRC is part of the CRC calculation.</p> <p>The messages above are received by an Intel 8274 chip. No CRC checking was done in the Intel chip though. </p> <p>Since the Intel 8274 chip do include a CRC checker/generator I should be able to both generate correctly formatted messages and to receive messages for further checking and investigation. I will pursue this path a bit to see if I could both receive and send using the 8274 chip and what CRC values that are generated.</p> <p>The 8274 chip itself supports two CRC algorithms. CRC-16 and CCITT CRC-16. My understanding is that IBM used CRC-16 with the polynomial X^16+X^15+X^2+1. I.e 8005. What initial value for crc was used is not described anywhere what I can see. A good guess though would be 0000h or possibly ffffh.</p> <p>The situation is that I would like to use a small STM32 micro controller to handle the BSC communications. I successfully had the program to achieve sync with the incoming data and extracted correctly formatted messages. But obviously communication would not work unless I can get the CRC calculation correct. WIP: <a href="https://github.com/MattisLind/alfaskop_emu/tree/master/Utils/BSCGateway" rel="nofollow noreferrer">https://github.com/MattisLind/alfaskop_emu/tree/master/Utils/BSCGateway</a></p> <p><strong>CRC reveng troubles</strong></p> <p>I have tried crc reveng tool to calculate CRC digits but I cannot get a match with the data above. Neither can I use crc reveng to search for an algorithm. It constantly reports that no models where found.</p> <p>Generating CRC using crc reveng with above messages as data in and polynomial 8005 doesn't give the corresponding output CRC data. I tried several initial values for CRC and also tested various variants of options for bit order but no match.</p> <p>Then I tried a few CRC algorithms in C found on internet. They all gave the same CRC value on the above messages but non of them matched the values in the messages neither the output from crc reveng.</p> <p>It is very likely that I have done something wrong when applying crc reveng, but I cannot figure out what.</p> <p><strong>Another test of crc reveng</strong></p> <p>Just to get a better understanding of crc reveng I tried a sample message where the input data buffer, initial CRC value and output CRC value was well known: <a href="https://stackoverflow.com/questions/23638939/crc-16-ibm-reverse-lookup-in-c">https://stackoverflow.com/questions/23638939/crc-16-ibm-reverse-lookup-in-c</a></p> <p>The code in the first answer by Mark Adler give a result which is matching what is mentioned in the Maxim article. But I cannot recreate it in crc reveng, unfortunately.</p> <p>Hints on what I am doing wrong, please!</p>
Reverse engineering the IBM BSC (Bisync) protocol
|serial-communication|crc|
<p>One common issue I’ve seen in real programs is the NULL pointer which has the same value as the integer 0. For example, currently (2020) the Hex-Rays decompiler does not support one variable holding different types so for example when a register initialized with zero is used as integer in one branch and as pointer in another, you might see “funny” output. Alas I don’t have an example at hand but if I see it again I’ll add it here. </p> <p>Another thing that comes to mind is the “clever” implementation of double linked list using one field to store both next and previous pointers, known as <a href="https://en.wikipedia.org/wiki/XOR_linked_list" rel="nofollow noreferrer">XOR Linked List</a>. This pattern is probably about impossible to recover automatically but luckily it seems to be more of a theoretical curiosity than practical construct. </p>
23127
2020-01-27T22:53:30.530
<p>In <em><a href="https://pdfs.semanticscholar.org/4815/f4122fa6c83b1691fde8b4ce21775d400c59.pdf" rel="nofollow noreferrer">TIE: Principled Reverse Engineering of Types in Binary Programs</a></em>, Lee J. et al claim to solve most of the challenges in the process of C code decompilation that come with type reconstruction.</p> <p>While producing a complex type where maybe a <code>void *</code> could fit is definitely non-trivial, I was just thinking about a possible type recovery ambiguity for what merely concerns a variable of type <code>int</code> or <code>int *</code>.</p> <pre><code>int foo(int *a, int sz) { int res = 0; for (int *q = a; q &lt; &amp;a[sz]; q++) res += *q; return res; } </code></pre> <p>In 32-bit architectures, the above code shows an example of such ambiguity for variable <code>res</code>, as both <code>int</code> and <code>int *</code> are compatible with a 32-bit register, and the disassembled code is the same. If <code>res</code> was a pointer though, it would be improperly used since we would be returning the address of an automatic variable (and would lead to undefined behaviour). </p> <p>So can this example really be taken into account (is a valid instance)? Can you come up with an example where these two types generate ambiguity but are correctly used? Can we conclude that a variable can be inferred to be a pointer or not if it just gets dereferenced?</p>
Type reconstruction ambiguity
|ida|decompilation|type-reconstruction|
<pre><code>osboxes@osboxes:~/proto/bin$ ll | grep stack0 -rwsr-xr-x 1 root root 22412 Jan 22 07:16 stack0* osboxes@osboxes:~/proto/bin$ ./stack0 bash: ./stack0: No such file or directory </code></pre> <p>The program is marked as executable, but trying to execute it says there is no such file or directory. I didn't even notice it, because radare2 and gdb were able to execute it.</p> <p>After reading <a href="https://askubuntu.com/questions/133389/no-such-file-or-directory-but-the-file-exists">stackoverflow 1</a> and <a href="https://stackoverflow.com/questions/2716702/no-such-file-or-directory-error-when-executing-a-binary">stackoverflow 2</a>, it seems that the problem is that my 64 bit system can't handle the 32 bit executable.</p> <p>After running the following command, I got the executable to work. <code>sudo apt-get install lib32z1</code></p> <p>And also edb started working.</p> <hr> <p>Edit: Another reason why it might not work for you is that you have not marked it as executable. In that case:</p> <p><code>chmod +x filename</code></p>
23132
2020-01-28T12:27:07.603
<h2>Problem:</h2> <p>When I try to open an executable (in this case exploit exercises protostar stack0), then the following message appears in a pop-up box:</p> <p><code>Failed to open and attach to process: execv() failed: No such file or directory.</code></p> <p>and I am unable to open any files because of this.</p> <p>Terminal output:</p> <pre><code>osboxes@osboxes:~/tools/edb-debugger/build$ ./edb --run ~/proto/bin/stack0 Icon theme "elementary" not found. Starting edb version: 1.1.0 Please Report Bugs &amp; Requests At: https://github.com/eteran/edb-debugger/issues Running Terminal: "/usr/bin/xterm" Terminal Args: ("-title", "edb output", "-hold", "-e", "sh", "-c", "tty &gt; /tmp/edb_temp_file_787768528_7578;trap \"\" INT QUIT TSTP;exec&lt;&amp;-; exec&gt;&amp;-;while :; do sleep 3600; done") Terminal process has TTY: "/dev/pts/5" comparing versions: [4352] [4352] </code></pre> <p>At first I installed edb using apt-get. This problem occurred. Then I uninstalled and installed it manually from the source code (and fixed the segmentation fault issue by changing the plugins directory). The problem remains. It doesn't matter if I use --run or try to open it from the GUI.</p> <h2>Version info</h2> <p>I'm using Lubuntu. Linux 5.3.0-18. It's a VM downloaded from OSBoxes. </p>
Evan's debugger (edb) - Failed to open and attach to process: execv() failed: No such file or directory
|debuggers|
<p>DOS/4GW executables normally use LE (linear executable) format for the actual main program (the DOS stub is just a launcher for the DOS4GW.EXE extender) and should be detected as such by IDA so you can probably just check the loaded file format. </p>
23142
2020-01-29T05:59:06.437
<p>So far I batch disassembled all files using following PowerShell and IDA:</p> <pre><code>$files = Get-Content S:\files.txt ForEach ($file in $files) { Write-Host "Processing $file" &amp;"C:\Program Files\IDA Pro 7.4\ida.exe" -B $file } </code></pre> <p>I then did a simple processing to try and identify DOS APIs used:</p> <pre><code>$files = Get-ChildItem -Path S:\ -Filter *.asm -Recurse $ApiNames = @() ForEach ($file in $files) { Write-Host "Processing $file" $content = Get-Content $file.Fullname $APIs = $content | Where-Object { $_.Contains(" int ") } ForEach($API in $APIs) { if ($API.Contains(";")) { $split = $API.Split(";").Trim().Replace(" ", " ") $ApiName = "$($split[0]) - $($split[1])" $ApiName = $ApiName.Replace("- -","-").Trim() if ($apiName -eq "int 3 - software interrupt to invoke the debugger") { $apiName = "int 3 - Trap to Debugger" } if (!$ApiName.EndsWith(" -")) { if (!$ApiNames.Contains($ApiName)) { $ApiNames += $ApiName } } } } } $SortedApiNames = $ApiNames | Sort-Object $table = New-Object System.Data.DataTable $table.Columns.Add("Process") ForEach ($ApiName in $SortedApiNames) { $table.Columns.Add($ApiName) } ForEach ($file in $files) { Write-Host "Processing $file" $content = Get-Content $file.Fullname $APIs = $content | Where-Object { $_.Contains(" int ") } $row = @() $row+= $file.FullName $ApiList = @() ForEach($API in $APIs) { if ($API.Contains(";")) { $split = $API.Split(";").Trim().Replace(" ", " ") $ApiName = "$($split[0]) - $($split[1])" $ApiName = $ApiName.Replace("- -","-").Trim() if ($apiName -eq "int 3 - software interrupt to invoke the debugger") { $apiName = "int 3 - Trap to Debugger" } $ApiList+=$ApiName } } For($i=1;$i -lt $table.Columns.Count;$i++) { if ($ApiList.Contains($table.Columns[$i].ColumnName)) { $row+= "Yes" } else { $row+="No" } } $table.Rows.Add($row) } $table | Export-Csv -NoTypeInformation APIUse.csv </code></pre> <p>This identified the following interrupt calls used:</p> <pre><code>int 0C7h - used by BASIC while in interpreter int 0Dh - IRQ5 - FIXED DISK (PC), LPT2 (AT/PS) int 0E4h - used by BASIC while in interpreter int 0Fh - IRQ7 - PRINTER INTERRUPT int 10h - VIDEO - ALTERNATE FUNCTION SELECT (PS, EGA, VGA, MCGA) - GET EGA INFO int 10h - VIDEO - DISPLAY COMBINATION (PS,VGA/MCGA): read display combination code int 10h - VIDEO - GET CURRENT VIDEO MODE int 10h - VIDEO - GET INDIVIDUAL PALETTE REGISTER (VGA) int 10h - VIDEO - INSTALLATION CHECK (Video7 VGA,VEGA VGA) int 10h - VIDEO - Microsoft Mouse driver EGA support - WRITE ONE REGISTER int 10h - VIDEO - READ ATTRIBUTES/CHARACTER AT CURSOR POSITION int 10h - VIDEO - READ CURSOR POSITION int 10h - VIDEO - READ INDIVIDUAL DAC REGISTER (EGA, VGA/MCGA) int 10h - VIDEO - SCROLL PAGE UP int 10h - VIDEO - SELECT DISPLAY PAGE int 10h - VIDEO - SET CURSOR CHARACTERISTICS int 10h - VIDEO - SET CURSOR POSITION int 10h - VIDEO - SET INDIVIDUAL DAC REGISTER (EGA, VGA/MCGA) int 10h - VIDEO - SET VIDEO MODE int 10h - VIDEO - WRITE ATTRIBUTES/CHARACTERS AT CURSOR POSITION int 10h - VIDEO - WRITE CHARACTERS ONLY AT CURSOR POSITION int 11h - EQUIPMENT DETERMINATION int 15h - Get Extended Memory Size int 15h - SYSTEM - GET CONFIGURATION (XT after 1/10/86,AT mdl 3x9,CONV,XT286,PS) int 16h - KEYBOARD - CHECK BUFFER, DO NOT CLEAR int 16h - KEYBOARD - GET SHIFT STATUS int 16h - KEYBOARD - READ CHAR FROM BUFFER, WAIT IF EMPTY int 1Ah - CLOCK - GET TIME OF DAY int 20h - DOS - PROGRAM TERMINATION int 21h - DOS - 2+ - ADJUST MEMORY BLOCK SIZE (SETBLOCK) int 21h - DOS - 2+ - ALLOCATE MEMORY int 21h - DOS - 2+ - CHANGE THE CURRENT DIRECTORY (CHDIR) int 21h - DOS - 2+ - CLOSE A FILE WITH HANDLE int 21h - DOS - 2+ - CREATE A FILE WITH HANDLE (CREAT) int 21h - DOS - 2+ - CREATE A SUBDIRECTORY (MKDIR) int 21h - DOS - 2+ - CREATE DUPLICATE HANDLE (DUP) int 21h - DOS - 2+ - DELETE A FILE (UNLINK) int 21h - DOS - 2+ - FIND FIRST ASCIZ (FINDFIRST) int 21h - DOS - 2+ - FIND NEXT ASCIZ (FINDNEXT) int 21h - DOS - 2+ - FORCE DUPLICATE HANDLE (FORCDUP,DUP2) int 21h - DOS - 2+ - FREE MEMORY int 21h - DOS - 2+ - GET COUNTRY-DEPENDENT INFORMATION int 21h - DOS - 2+ - GET CURRENT DIRECTORY int 21h - DOS - 2+ - GET DISK SPACE int 21h - DOS - 2+ - GET EXIT CODE OF SUBPROGRAM (WAIT) int 21h - DOS - 2+ - GET FILE ATTRIBUTES int 21h - DOS - 2+ - GET FILE'S DATE/TIME int 21h - DOS - 2+ - GET INTERRUPT VECTOR int 21h - DOS - 2+ - GET VERIFY FLAG int 21h - DOS - 2+ - IOCTL - GET DEVICE INFORMATION int 21h - DOS - 2+ - IOCTL - READ CHARACTER DEVICE CONTROL STRING int 21h - DOS - 2+ - IOCTL - SET DEVICE INFORMATION int 21h - DOS - 2+ - LOAD OR EXECUTE (EXEC) int 21h - DOS - 2+ - MOVE FILE READ/WRITE POINTER (LSEEK) int 21h - DOS - 2+ - OPEN DISK FILE WITH HANDLE int 21h - DOS - 2+ - QUIT WITH EXIT CODE (EXIT) int 21h - DOS - 2+ - READ FROM FILE WITH HANDLE int 21h - DOS - 2+ - REMOVE A DIRECTORY ENTRY (RMDIR) int 21h - DOS - 2+ - RENAME A FILE int 21h - DOS - 2+ - SET FILE ATTRIBUTES int 21h - DOS - 2+ - SET FILE'S DATE/TIME int 21h - DOS - 2+ - WRITE TO FILE WITH HANDLE int 21h - DOS - 2+ internal - GET LIST OF LISTS int 21h - DOS - 2+ internal - GET SWITCHAR/AVAILDEV int 21h - DOS - 2+ internal - RETURN CritSectFlag (InDOS) POINTER int 21h - DOS - 2+ internal - SET PSP SEGMENT int 21h - DOS - 3.1+ internal - GET ADDRESS OF DOS SWAPPABLE DATA AREA int 21h - DOS - 3+ - CREATE NEW FILE int 21h - DOS - 3+ - GET EXTENDED ERROR CODE int 21h - DOS - 3+ - GET PSP ADDRESS int 21h - DOS - 4.0 - EXTENDED OPEN/CREATE int 21h - DOS - BUFFERED KEYBOARD INPUT int 21h - DOS - CLEAR KEYBOARD BUFFER int 21h - DOS - DIRECT CONSOLE I/O CHARACTER OUTPUT int 21h - DOS - DIRECT STDIN INPUT, NO ECHO int 21h - DOS - DISK RESET int 21h - DOS - DISPLAY OUTPUT int 21h - DOS - DOS 2+ - TERMINATE BUT STAY RESIDENT int 21h - DOS - DOS v??? - OEM FUNCTION int 21h - DOS - EXTENDED CONTROL-BREAK CHECKING int 21h - DOS - GET ALLOCATION TABLE INFORMATION FOR SPECIFIC DRIVE int 21h - DOS - GET CURRENT DATE int 21h - DOS - GET CURRENT TIME int 21h - DOS - GET DEFAULT DISK NUMBER int 21h - DOS - GET DISK TRANSFER AREA ADDRESS int 21h - DOS - GET DOS VERSION int 21h - DOS - KEYBOARD INPUT int 21h - DOS - KEYBOARD INPUT, NO ECHO int 21h - DOS - Novell Advanced NetWare 2.0+ - FILE SERVER FILE COPY int 21h - DOS - PARSE FILENAME int 21h - DOS - PRINT STRING int 21h - DOS - SELECT DISK int 21h - DOS - SET CURRENT DATE int 21h - DOS - SET CURRENT TIME int 21h - DOS - SET DISK TRANSFER AREA ADDRESS int 21h - DOS - SET INTERRUPT VECTOR int 21h - DOS - SET VERIFY FLAG int 2Fh - Multiplex - MS WINDOWS - 3+ - BEGIN CRITICAL SECTION int 2Fh - Multiplex - MS WINDOWS - ENHANCED WINDOWS INSTALLATION CHECK int 2Fh - Multiplex - MS WINDOWS - Mode Interface - INSTALLATION CHECK int 2Fh - Multiplex - XMS - GET DRIVER ADDRESS int 2Fh - Multiplex - XMS - INSTALLATION CHECK int 3 - Trap to Debugger int 31h - DPMI Services ax=func xxxxh int 33h - MS MOUSE - DEFINE DOUBLE-SPEED THRESHOLD int 33h - MS MOUSE - DEFINE INTERRUPT SUBROUTINE PARAMETERS int 33h - MS MOUSE - DEFINE SCREEN REGION FOR UPDATING int 33h - MS MOUSE - DEFINE TEXT CURSOR int 33h - MS MOUSE - HIDE MOUSE CURSOR int 33h - MS MOUSE - POSITION MOUSE CURSOR int 33h - MS MOUSE - READ MOTION COUNTERS int 33h - MS MOUSE - RESET DRIVER AND READ STATUS int 33h - MS MOUSE - RESTORE DRIVER STATE int 33h - MS MOUSE - RETURN DRIVER STORAGE REQUIREMENTS int 33h - MS MOUSE - RETURN POSITION AND BUTTON STATUS int 33h - MS MOUSE - SAVE DRIVER STATE int 33h - MS MOUSE - SHOW MOUSE CURSOR int 3Fh - Overlay manager interrupt int 48h - PCjr - Cordless Keyboard Translation int 67h - LIM EMS - GET HANDLE AND ALLOCATE MEMORY int 67h - LIM EMS - GET NUMBER OF PAGES int 67h - LIM EMS - GET PAGE FRAME SEGMENT int 67h - LIM EMS - MAP MEMORY int 67h - LIM EMS - RELEASE HANDLE AND MEMORY int 67h - LIM EMS 4.0 - REALLOCATE PAGES int 67h - LIM EMS Program Interface - FREE 4K PAGE int 67h - LIM EMS Program Interface - GET 8259 INTERRUPT VECTOR MAPPINGS int 67h - LIM EMS Program Interface - GET PROTECTED MODE INTERFACE int 67h - LIM EMS Program Interface - INSTALLATION CHECK int 67h - LIM EMS Program Interface - SWITCH TO PROTECTED MODE int 75h - IRQ13 - AT/XT286/PS50+ - 80287 ERROR int 7Ah - Novell NetWare to v2.0a - LOW-LEVEL API int 89h - used by BASIC while in interpreter int 8Ch - used by BASIC while in interpreter int 91h - used by BASIC while in interpreter int 98h - used by BASIC while in interpreter </code></pre> <p>What can I look for to confirm if an app uses DOS/4GW?</p>
Within A Folder of 100s of 16-bit MS-DOS Disassembled EXEs Identify Ones That Need/Use DOS/4GW
|disassembly|dos|dos-exe|
<p>The <code>.data</code> is filled with relocation information at load time. </p> <p>from <code>IDA</code>:</p> <pre><code>LOAD:0000000000000598 08 20 01 00+ Elf64_Rela &lt;0x12008, 0x403, 0x11EF&gt; ; R_AARCH64_RELATIVE LOAD:00000000000005B0 10 20 01 00+ Elf64_Rela &lt;0x12010, 0x403, 0x1200&gt; ; R_AARCH64_RELATIVE LOAD:00000000000005C8 18 20 01 00+ Elf64_Rela &lt;0x12018, 0x403, 0xC48&gt; ; R_AARCH64_RELATIVE LOAD:00000000000005E0 20 20 01 00+ Elf64_Rela &lt;0x12020, 0x403, 0x127B&gt; ; R_AARCH64_RELATIVE LOAD:00000000000005F8 28 20 01 00+ Elf64_Rela &lt;0x12028, 0x403, 0x128B&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000610 30 20 01 00+ Elf64_Rela &lt;0x12030, 0x403, 0xEE8&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000628 38 20 01 00+ Elf64_Rela &lt;0x12038, 0x403, 0x12F1&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000640 40 20 01 00+ Elf64_Rela &lt;0x12040, 0x403, 0x1300&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000658 48 20 01 00+ Elf64_Rela &lt;0x12048, 0x403, 0x1000&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000670 50 20 01 00+ Elf64_Rela &lt;0x12050, 0x403, 0x1305&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000688 58 20 01 00+ Elf64_Rela &lt;0x12058, 0x403, 0x1310&gt; ; R_AARCH64_RELATIVE LOAD:00000000000006A0 60 20 01 00+ Elf64_Rela &lt;0x12060, 0x403, 0x104C&gt; ; R_AARCH64_RELATIVE LOAD:00000000000006B8 68 20 01 00+ Elf64_Rela &lt;0x12068, 0x403, 0x1315&gt; ; R_AARCH64_RELATIVE LOAD:00000000000006D0 70 20 01 00+ Elf64_Rela &lt;0x12070, 0x403, 0x132B&gt; ; R_AARCH64_RELATIVE LOAD:00000000000006E8 78 20 01 00+ Elf64_Rela &lt;0x12078, 0x403, 0x1054&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000700 80 20 01 00+ Elf64_Rela &lt;0x12080, 0x403, 0x1334&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000718 88 20 01 00+ Elf64_Rela &lt;0x12088, 0x403, 0x132B&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000730 90 20 01 00+ Elf64_Rela &lt;0x12090, 0x403, 0x1074&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000748 98 20 01 00+ Elf64_Rela &lt;0x12098, 0x403, 0x134C&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000760 A0 20 01 00+ Elf64_Rela &lt;0x120A0, 0x403, 0x1359&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000778 A8 20 01 00+ Elf64_Rela &lt;0x120A8, 0x403, 0x1094&gt; ; R_AARCH64_RELATIVE LOAD:0000000000000790 B0 20 01 00+ Elf64_Rela &lt;0x120B0, 0x403, 0x1360&gt; ; R_AARCH64_RELATIVE LOAD:00000000000007A8 B8 20 01 00+ Elf64_Rela &lt;0x120B8, 0x403, 0x136F&gt; ; R_AARCH64_RELATIVE LOAD:00000000000007C0 C0 20 01 00+ Elf64_Rela &lt;0x120C0, 0x403, 0x10A8&gt; ; R_AARCH64_RELATIVE </code></pre> <p>You can see that every entry is corresponding to the data you see in the <code>.data</code> section.</p>
23154
2020-01-30T06:53:20.290
<p>My question is: Why does <code>readelf -x .data bin.so</code> give me empty data when ghidra does not? (0x00 repeated for section length until last element 0xFFFFFFFF). </p> <p>ghidra/JEB contradict me by showing that it has populated data (only first 8 bytes are null). I have tried python tools lief, elfcat, among others. </p> <p>Obtaining repro file:</p> <ol> <li>wget <a href="https://repo1.maven.org/maven2/com/facebook/fresco/imagepipeline/2.0.0/imagepipeline-2.0.0.aar" rel="nofollow noreferrer">https://repo1.maven.org/maven2/com/facebook/fresco/imagepipeline/2.0.0/imagepipeline-2.0.0.aar</a></li> <li>unzip imagepipeline-2.0.0.aar "jni/arm64-v8a/libimagepipeline.so</li> <li>readelf -x .data jni/arm64-v8a/libimagepipeline.so</li> <li>Load the elf into ghidra and confirm that the .data section (can be found by double clicking on .data in "Program Tree" on left(default) hand side) is populated with excellent data.</li> </ol>
empty .data section in AARCH64 elf binaries
|binary-analysis|binary|ghidra|arm64|
<p>That should be rather easy to solve in IDA with IDAPython or IDC.</p> <p>I remember plugins that name functions based on API calls happening inside for a quick overview, one example here:</p> <p><a href="https://reverseengineering.stackexchange.com/questions/9352/finding-all-api-calls-in-a-function">Finding all API calls in a function</a></p> <p>Essentially it does what you need but note there is no semantic check whatsoever. It just means these API calls appeared in the same function and could be entirely unrelated, but it gives a rough overview of API call chains happening together (by logic of being in the same function).</p> <p>If relation is important, it's a way harder problem as you'd need to track input/output from API calls (and for that know what the input/output for each API call is) and thus turning into a data flow analysis problem.</p>
23166
2020-02-01T10:03:14.903
<p>How does one extract the static API sequences of a PE file? I don't mean the imports listed in the imports segment. </p> <p>I am currently using different RE tools like Ghidra, IDA Pro, and Binary Ninja. None of which I know has a built-in feature which allows me to extract the static API sequences. </p> <p>[EDIT] I am looking for API call sequences without executing the binary. For example, maybe if the binary code contains file operations like fopen() → fwrite() → fclose() → fopen() → fwrite() → fclose(). I want to be able to extract this sequence of APIs.</p>
How to extract static API sequences of a PE file?
|ida|static-analysis|functions|api|
<p>Igor gave the answer for Ida. A more general possibility, very simple and working everywhere, would be just to write down a sequence of immutable bytes from the disassembler (i.e. avoiding changing addresses), then load the file into a Hex Editor and let it search for that sequence. If it is long enough there will mostly be only a single hit within the file.</p>
23177
2020-02-03T00:27:55.530
<p>I noticed that if I found an instruction in IDA, the address shown to its left would be wildly different from where it appears in the actual file. I wanted to know why this was the case and how I can find the offset in the file that each instruction corresponds to. Thanks!</p>
In IDA, why are the addresses of instructions different from the corresponding locations in the original file? How do I find the file locations?
|ida|pe|address|
<p>This should be the problem of the linker at compile time. These things are not solved dynamically but statically. It should produce an error of the kind <code>multiple definition</code> as illustrated on the following example (taken from <a href="https://stackoverflow.com/questions/36209788/gcc-multiple-definition-of-error">here</a>): </p> <pre><code>/tmp/ccscmcbS.o:(.bss+0x0): multiple definition of `global_base' /tmp/ccyjhjQC.o:(.bss+0x0): first defined here /tmp/ccscmcbS.o: In function `find_free_block': support.c:(.text+0x0): multiple definition of `find_free_block' /tmp/ccyjhjQC.o:main.c:(.text+0x0): first defined here /tmp/ccscmcbS.o: In function `request_space': support.c:(.text+0x55): multiple definition of `request_space' /tmp/ccyjhjQC.o:main.c:(.text+0x55): first defined here /tmp/ccscmcbS.o: In function `get_block_ptr': support.c:(.text+0xfe): multiple definition of `get_block_ptr' /tmp/ccyjhjQC.o:main.c:(.text+0xfe): first defined here collect2: error: ld returned 1 exit status </code></pre>
23194
2020-02-05T12:54:10.583
<p>From what I understand, the <code>ELF</code> format doesn't specify which symbols come from which file - Every <code>ELF</code> that uses import has a list of symbols to import and list of file names, and the loader is trying to locate those symbols in the file names. </p> <p>But what happens if there is a collision - the same symbol appears twice, in different files? Is it possible to somehow force by the <code>ELF</code> format the destination file to look for a specific symbol? </p>
ELF imported symbols colision
|elf|
<p>If there are code changes, it will most likely change between versions. </p> <p>I would suggest you look at the implementation of FLIRT, in particular <a href="https://www.hex-rays.com/products/ida/tech/flirt/in_depth/" rel="nofollow noreferrer">here</a>, where they explain how they face this issue. </p>
23199
2020-02-06T15:33:23.730
<p>So let's say we want to use some instructions as signature for a malware, and it includes some call instructions or jmp instructions. Now, as far as I have seen, they always contain relative offsets as address and don't contain absolute addresses of the destination.</p> <p>Now, can the relative offset between functions or instructions change if the binary is compiled again with the same compiler? How about with another compiler?</p> <p>Do you guys think using a call instruction as part of a signature is good?</p>
Can relative offsets in instructions like call and jmp change after recompiling the same code, or running it in another computer?
|assembly|decompilation|malware|static-analysis|operating-systems|
<p>From what you describe, there might be somewhere in the SW an obscure algorithm calculating the seed. If there is no pattern which can be found, you must find this algo in the software. Here are some hints how you could proceed:</p> <ul> <li><p>Start it from within a debugger like Ida and set a random breakpoint during the run. Try to analyze the structure of the code loaded in memory.</p></li> <li><p>If this does not work, start it and try to attach a debugger during the run and proceed like above.</p></li> <li><p>If this not work either, try to investigate the unpacker/decrypter. There must be an unencrypted stub where everything starts. Do not analyze line by line, but in blocks and try to identify the point where the whole thing is unencrypted loaded in memory. If this is hampered by anti-debug measures, these should be removed. In this stage much could be done statically. You could try a decompiler like Ghidra to make faster progress than with pure static disassembler.</p></li> <li><p>If you have more advanced software which decrypts in chunks and after having done its work encrypts again you will have a rather hard time to procedd. It is possible though.</p></li> <li><p>For your strategy of "guessing" the seeds, no general rule can be given here. If you are able to define a roadmap how to proceed this might work. If there is some kind of weird app specific algo I would much prefer the other - tedious but rather straightforward - possibilities.</p></li> </ul>
23203
2020-02-06T21:11:13.017
<p>I am trying to reverse a simple image format for bitmap data with an indexed colour palette. The structure of the file is generally clear and I am able to extract the size of the picture and the palette. The place of where the run-length encoded data is stored is also pretty clear. However, the software for editing these images encrypts the run-length encoded data in a simple way by XORing it.</p> <p>Through manipulation of the data and viewing it in the software, I am able to extract the pixel dependent key for the XOR function, i.e. if there are 9 pixels totally, there are 9 keys. The problem is, however, that everytime the file is saved in the software, the keys change. I have identified two bytes in the file that change together with the encrypted data everytime it is saved and I therefore expect that it must be some sort of seed for generating the keys.</p> <p>Nevertheless, after saving the same file many times, examining the seed and the xor keys, no clear pattern emerges. It is only obvious that the first pixel has always the same key, the second key can only change by 1 and the rest looks currently random to me. Shifting the seed and combining it with the first key or using modulo operations don't work.</p> <p>The software itself is packed/encrypted and I am unable to unpack it, i.e. I think I have to deduce the encryption solely based on the files I can generate. Is there some general advice on how to proceed in such a situation?</p>
Encrypted image format
|file-format|encryption|binary|
<p>The answer depends on what you mean by "Command Line Interface".</p> <p>You can pass a filename to the ida64 executable on command line and it will be opened. Some of the switches (like <code>-A</code>, <code>-T</code>, <code>-L</code>) also work, but for example <code>-B</code> and <code>-S</code> are disabled.</p> <p>If you want the text-mode <code>idat</code> executable, you need the full version (Pro or Starter).</p>
23208
2020-02-07T07:25:07.467
<p>Does anybody know if IDA's FreeWare version 7.0 has the Command Line Interface option?</p> <p>I currently have IDA FreeWare 7.0 and I only see one .exe file which is ida64.exe. But according to HexRay's command line switches for IDA Pro, there is supposed to be an .exe for command line interface. I'm not sure if it's just because I am using the free version. </p>
Does IDA Pro's Freeware version have a command line interface?
|ida|
<p>from your paste above I presume<br> You Want to get this data from the object files <strong>( *.obj )</strong> and not from the compiled and linked executable </p> <p>if yes then COFF (component object file format ) is pretty well documented all you need to parse is COFF SYMBOL TABLE </p> <p>you can use dumpbin /SYMBOLS to look for all functions </p> <pre><code>C:\Users\xx\source\repos\dumpfuncs&gt;dumpbin /symbols dumpfuncs.obj | grep -i ( Microsoft (R) COFF/PE Dumper Version 14.16.27035.0 Copyright (C) Microsoft Corporation. All rights reserved. 010 00000000 SECT5 notype () External | ?CmdLn@@YAPADXZ (char * __cdecl CmdLn(void)) 011 00000010 SECT5 notype () External | ?FileName@@YAPADXZ (char * __cdecl FileName(void)) 012 00000020 SECT5 notype () External | _main </code></pre> <p>Raw Parsing of an obj file with a hex dumper (xxd.exe)</p> <pre><code>:\&gt;xxd -v xxd v1.11, 8 jun 2013 by Juergen Weigert et al. &lt;&lt;&lt;&lt;&lt; has little endian switch -e </code></pre> <p>COFF_SYMBOL_TABLE is at offset 8 in COFF HEADER followed by number of symbols </p> <pre><code>:\&gt;xxd.exe -e -l 8 -g 4 -s 8 dumpfuncs.obj 00000008: 000048c0 00000015 .H...... </code></pre> <p>keep dumping 0x12 bytes for each symbol and their aux records if any </p> <p>SYMBOL 1</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x48c0 -l 18 dumpfuncs.obj 000048c0: 40 63 6f 6d 70 2e 69 64 9b 69 05 01 ff ff 00 00 03 00 @comp.id.i........ </code></pre> <p>SYMBOL 2</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x48d2 -l 18 dumpfuncs.obj 000048d2: 40 66 65 61 74 2e 30 30 91 01 00 80 ff ff 00 00 03 00 @feat.00.......... </code></pre> <p>SYMBOL 3,4</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x48e4 -l 18 dumpfuncs.obj 000048e4: 2e 64 72 65 63 74 76 65 00 00 00 00 01 00 00 00 03 01 .drectve.......... :\&gt;echo one auxillary record follows (last byte is 01) do not count as symbol :\&gt;xxd -g 1 -c 18 -s 0x48f6 -l 18 dumpfuncs.obj 000048f6: 91 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .................. </code></pre> <p>SYMBOL 5,6</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x4908 -l 18 dumpfuncs.obj 00004908: 2e 64 65 62 75 67 24 53 00 00 00 00 02 00 00 00 03 01 .debug$S.......... :\&gt;xxd -g 1 -c 18 -s 0x491a -l 18 dumpfuncs.obj 0000491a: 50 45 00 00 15 00 00 00 00 00 00 00 00 00 00 00 00 00 PE................ </code></pre> <p>SYMBOL 7,8</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x492c -l 18 dumpfuncs.obj 0000492c: 2e 64 65 62 75 67 24 54 00 00 00 00 03 00 00 00 03 01 .debug$T.......... :\&gt;xxd -g 1 -c 18 -s 0x493e -l 18 dumpfuncs.obj 0000493e: 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 L................. </code></pre> <p>SYMBOL 9,0xa</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x4950 -l 18 dumpfuncs.obj 00004950: 2e 72 64 61 74 61 00 00 00 00 00 00 04 00 00 00 03 01 .rdata............ :\&gt;xxd -g 1 -c 18 -s 0x4962 -l 18 dumpfuncs.obj 00004962: 0e 00 00 00 00 00 00 00 ad 41 9d c2 00 00 00 00 00 00 .........A........ </code></pre> <p>SYMBOL 0xb</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x4974 -l 18 dumpfuncs.obj 00004974: 24 53 47 38 39 31 38 32 00 00 00 00 04 00 00 00 03 00 $SG89182.......... </code></pre> <p>SYMBOL 0xc,----0x13</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x4986 -l 18 dumpfuncs.obj 00004986: 2e 74 65 78 74 24 6d 6e 00 00 00 00 05 00 00 00 03 01 .text$mn.......... :\&gt;xxd -g 1 -c 18 -s 0x4998 -l 18 dumpfuncs.obj 00004998: 43 00 00 00 06 00 00 00 7d 5c d3 64 00 00 00 00 00 00 C.......}\.d...... the six relocations in section #5 whose size of rawdata is 43 the start and end address of section Raw Data is in COFF_HEADER :\&gt;xxd -g 1 -c 18 -s 0x49aa -l 18 dumpfuncs.obj 000049aa: 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 02 00 .................. :\&gt;xxd -g 1 -c 18 -s 0x49bc -l 18 dumpfuncs.obj 000049bc: 00 00 00 00 1d 00 00 00 00 00 00 00 00 00 00 00 02 00 .................. :\&gt;xxd -g 1 -c 18 -s 0x49ce -l 18 dumpfuncs.obj 000049ce: 00 00 00 00 32 00 00 00 00 00 00 00 00 00 00 00 02 00 ....2............. :\&gt;xxd -g 1 -c 18 -s 0x49e0 -l 18 dumpfuncs.obj 000049e0: 00 00 00 00 48 00 00 00 00 00 00 00 05 00 20 00 02 00 ....H......... ... :\&gt;echo the 20 denotes a function in section #5 name of function is at 0x48 from string table :\&gt;xxd -g 1 -c 18 -s 0x49f2 -l 18 dumpfuncs.obj 000049f2: 00 00 00 00 58 00 00 00 10 00 00 00 05 00 20 00 02 00 ....X......... ... :\&gt;echo funcname @58 in section 5 10 bytes from start :\&gt;xxd -g 1 -c 18 -s 0x4a04 -l 18 dumpfuncs.obj 00004a04: 5f 6d 61 69 6e 00 00 00 20 00 00 00 05 00 20 00 02 00 _main... ..... ... :\&gt;echo main() starts at offset 20 insection #5 </code></pre> <p>SYMBOL 0x14,0x15</p> <pre><code>:\&gt;xxd -g 1 -c 18 -s 0x4a16 -l 18 dumpfuncs.obj 00004a16: 2e 63 68 6b 73 36 34 00 00 00 00 00 06 00 00 00 03 01 .chks64........... :\&gt;xxd -g 1 -c 18 -s 0x4a28 -l 18 dumpfuncs.obj 00004a28: 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0................. </code></pre> <p>:>echo 0x15 symbols and thier aux records are over now string table starts</p> <pre><code>:\&gt;xxd -e -g 4 -s 0x4a3a -l 4 dumpfuncs.obj 00004a3a: 0000006b k... :\&gt;echo size of string table 0x6b :\&gt;xxd -e -g 1 -s 0x4a3a -l 0x6b dumpfuncs.obj 00004a3a: 6b 00 00 00 5f 5f 69 6d 70 5f 5f 47 65 74 43 6f k...__imp__GetCo 00004a4a: 6d 6d 61 6e 64 4c 69 6e 65 41 40 30 00 5f 5f 69 mmandLineA@0.__i 00004a5a: 6d 70 5f 5f 45 78 69 74 50 72 6f 63 65 73 73 40 mp__ExitProcess@ 00004a6a: 34 00 5f 5f 69 6d 70 5f 5f 4d 65 73 73 61 67 65 4.__imp__Message 00004a7a: 42 6f 78 41 40 31 36 00 3f 43 6d 64 4c 6e 40 40 BoxA@16.?CmdLn@@ 00004a8a: 59 41 50 41 44 58 5a 00 3f 46 69 6c 65 4e 61 6d YAPADXZ.?FileNam 00004a9a: 65 40 40 59 41 50 41 44 58 5a 00 e@@YAPADXZ. </code></pre> <p>The Demangled Name of Function At offset 0x48 from string table start</p> <pre><code>:\&gt;xxd -g 1 -s 0x4a82 -l 0x10 dumpfuncs.obj 00004a82: 3f 43 6d 64 4c 6e 40 40 59 41 50 41 44 58 5a 00 ?CmdLn@@YAPADXZ. </code></pre> <p>unmangled name </p> <pre><code>:\&gt;vc++filt ?CmdLn@@YAPADXZ char * __cdecl CmdLn(void) ^C </code></pre> <p>Section #5 Header and Raw Data</p> <pre><code>:\&gt;xxd -g 4 -c 4 -e -s 0xb4 -l 0x28 dumpfuncs.obj 000000b4: 7865742e .tex 000000b8: 6e6d2474 t$mn 000000bc: 00000000 .... 000000c0: 00000000 .... 000000c4: 00000043 C... 000000c8: 00004811 .H.. 000000cc: 00004854 TH.. 000000d0: 00000000 .... 000000d4: 00000006 .... 000000d8: 60500020 .P` :\&gt;xxd -g 1 -s 0x4811 -l 0x43 dumpfuncs.obj 00004811: 55 8b ec ff 15 00 00 00 00 5d c3 cc cc cc cc cc U........]...... 00004821: 55 8b ec b8 00 00 00 00 5d c3 cc cc cc cc cc cc U.......]....... 00004831: 55 8b ec 6a 00 e8 00 00 00 00 50 e8 00 00 00 00 U..j......P..... 00004841: 50 6a 00 ff 15 00 00 00 00 6a 00 ff 15 00 00 00 Pj.......j...... 00004851: 00 5d c3 .]. :\&gt;echo notice the push ebp prolog notice the push ebp prolog </code></pre> <p>Raw Data Dis Assembled</p> <pre><code>&gt;dumpbin /disasm dumpfuncs.obj ?CmdLn@@YAPADXZ (char * __cdecl CmdLn(void)): 00000000: 55 push ebp 00000001: 8B EC mov ebp,esp 00000003: FF 15 00 00 00 00 call dword ptr [__imp__GetCommandLineA@0] 00000009: 5D pop ebp 0000000A: C3 ret 0000000B: CC int 3 0000000C: CC int 3 0000000D: CC int 3 0000000E: CC int 3 0000000F: CC int 3 ?FileName@@YAPADXZ (char * __cdecl FileName(void)): 00000010: 55 push ebp 00000011: 8B EC mov ebp,esp 00000013: B8 00 00 00 00 mov eax,offset $SG89182 00000018: 5D pop ebp 00000019: C3 ret 0000001A: CC int 3 0000001B: CC int 3 0000001C: CC int 3 0000001D: CC int 3 0000001E: CC int 3 0000001F: CC int 3 _main: 00000020: 55 push ebp 00000021: 8B EC mov ebp,esp 00000023: 6A 00 push 0 00000025: E8 00 00 00 00 call ?FileName@@YAPADXZ 0000002A: 50 push eax 0000002B: E8 00 00 00 00 call ?CmdLn@@YAPADXZ 00000030: 50 push eax 00000031: 6A 00 push 0 00000033: FF 15 00 00 00 00 call dword ptr [__imp__MessageBoxA@16] 00000039: 6A 00 push 0 0000003B: FF 15 00 00 00 00 call dword ptr [__imp__ExitProcess@4] 00000041: 5D pop ebp 00000042: C3 ret </code></pre> <p>the source used for compiling and linking with vs 2017</p> <pre><code>#include &lt;windows.h&gt; #pragma comment(lib,"user32.lib") #pragma comment(lib,"kernel32.lib") __declspec ( noinline ) LPSTR CmdLn(void) { return GetCommandLineA(); } __declspec ( noinline ) LPSTR FileName (void) { return __FILE__; } int main(void) { MessageBoxA(NULL,CmdLn(),FileName(), MB_OK); ExitProcess(NULL); } </code></pre> <p>compiled and linked with</p> <pre><code>cl /Zi /W4 /analyze /EHsc /nologo /Od %1.cpp /link /release /subsystem:windows /entry:main </code></pre>
23211
2020-02-07T12:37:59.843
<p><strong>How can I find only real functions not data garbage like section..debug_S_105 ? *</strong></p> <p>I need to collect function data (assembler code) of Open Source C++ Files which I compile with Visual Studio 19 (sln file was provided). </p> <p>For example I generated <a href="https://github.com/weidai11/cryptopp" rel="nofollow noreferrer">cryptopp library</a> --> opened provided <a href="https://github.com/weidai11/cryptopp/blob/master/cryptest.sln" rel="nofollow noreferrer">cryptest.sln</a> and built it (Win32, Release, /O2) which produces some files:<br> - Object files: 3way.obj, adler32.obj, algebra.obj,<br> - Lib file: cryptlib.lib<br> - PDB file: cryptlib.pdb </p> <p>I need to know the function name and get the assembler code:</p> <pre><code>xxxx ✗ r2 authenc.obj [0x0000368d]&gt; aaaa [Cannot analyze at 0x00010bdeg with sym. and entry0 (aa) Cannot analyze at 0x00010be2 Cannot analyze at 0x00010c08 Cannot analyze at 0x00010c08 Cannot analyze at 0x00010c1a Cannot analyze at 0x00010c1a Cannot analyze at 0x00010d28 Cannot analyze at 0x00010d28 Cannot analyze at 0x0001114e Cannot analyze at 0x0001114e [...] Cannot analyze at 0x000111fd Cannot analyze at 0x000111fd Cannot analyze at 0x00011211 Cannot analyze at 0x00011211 Cannot analyze at 0x0001126f Cannot analyze at 0x0001126f Cannot analyze at 0x00011283 Cannot analyze at 0x00011283 [x] Analyze all flags starting with sym. and entry0 (aa) [x] Analyze function calls (aac) [x] Analyze len bytes of instructions for references (aar) [x] Check for objc references [x] Check for vtables [x] Type matching analysis for all functions (aaft) [x] Propagate noreturn information [x] Use -AA or aaaa to perform additional experimental analysis. [x] Finding function preludes [x] Enable constraint types analysis for variables [0x0000368d]&gt; afl 0x0000368d 5 63 sym.____HDU__char_traits_D_std__V__allocator_D_1__std__YA_AV__basic_string_DU__char_traits_D_std__V__allocator_D_2__0___QAV10_0_Z 0x00000000 45 877 -&gt; 848 sym._comp.id 0x00001b44 286 1517 -&gt; 1781 sym..drectve 0x00003619 62 851 -&gt; 946 sym..debug_T 0x00003980 25 601 -&gt; 640 section..debug_S_6 0x00003c15 81 872 -&gt; 951 section..debug_S_8 0x000040e7 3 25 sym.__unwindfunclet_____HDU__char_traits_D_std__V__allocator_D_1__std__YA_AV__basic_string_DU__char_traits_D_std__V__allocator_D 0x00004143 5 34 sym.____Allocate__07U_Default_allocate_traits_std___0A__std__YAPAXI_Z 0x00004179 20 447 -&gt; 510 section..debug_S_11 0x000043a7 16 291 -&gt; 307 sym.____Allocate_manually_vector_aligned_U_Default_allocate_traits_std___std__YAPAXI_Z 0x000046a8 3 44 sym.____Deallocate__07_0A__std__YAXPAXI_Z 0x000046e8 19 638 -&gt; 633 section..debug_S_15 0x000049a2 91 1191 -&gt; 1310 section..debug_S_17 0x000051f4 6 134 sym.____Reallocate_grow_by_V_lambda_67d87d4aa1269033985980465fd1d824_____V___basic_string_DU__char_traits_D_std__V__allocator_D_2 0x000052b6 77 2130 -&gt; 2150 section..debug_S_19 0x00005b58 98 1887 -&gt; 1975 section..debug_S_21 0x0000644a 1 46 sym.__0__basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAE___QAV01__Z 0x00006478 38 1037 -&gt; 1080 section..debug_S_23 0x00006899 14 258 -&gt; 254 fcn.00006899 0x00006a73 1 172 sym.__0BadState_AuthenticatedSymmetricCipher_CryptoPP__QAE_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std__PBD1_Z 0x00006bbf 275 1521 -&gt; 1789 section..debug_S_27 0x000073a9 8 138 -&gt; 140 fcn.000073a9 0x0000743e 1 105 sym.__0BadState_AuthenticatedSymmetricCipher_CryptoPP__QAE_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std__PBD_Z 0x0000750b 152 971 -&gt; 1135 section..debug_S_30 0x00007a6d 4 184 fcn.00007a6d 0x00007b61 37 453 -&gt; 508 section..debug_S_33 0x00007ef3 3 142 sym.__unwindfunclet___0Exception_CryptoPP__QAE_ABV01__Z_0 0x00007fb3 92 797 -&gt; 928 section..debug_S_36 0x00008409 3 106 sym.__unwindfunclet___0Exception_CryptoPP__QAE_W4ErrorType_01_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std___Z 0x00008487 23 491 -&gt; 519 section..debug_S_39 0x00008686 19 559 -&gt; 578 section..debug_S_41 0x000088c9 136 2578 -&gt; 2731 section..debug_S_43 0x0000913c 12 415 -&gt; 432 section..debug_S_53 0x000092f9 64 1036 -&gt; 1135 section..debug_S_55 0x00009817 3 31 sym.___GBadState_AuthenticatedSymmetricCipher_CryptoPP__UAEPAXI_Z 0x0000984a 42 417 -&gt; 504 section..debug_S_57 0x000099ff 26 377 -&gt; 423 section..debug_S_59 0x00009b8c 25 404 -&gt; 418 section..debug_S_61 0x00009d3e 20 355 -&gt; 378 section..debug_S_63 0x00009ec8 16 188 sym._AuthenticateData_AuthenticatedSymmetricCipherBase_CryptoPP__IAEXPBEI_Z 0x00009fa2 64 2101 -&gt; 2160 section..debug_S_65 0x0000a881 204 1185 -&gt; 1293 section..debug_S_67 0x0000b213 8 287 sym.__unwindfunclet__ProcessData_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPAEPBEI_Z_3 0x00000068 51 773 -&gt; 769 fcn.00000068 0x00000008 45 869 -&gt; 840 fcn.00000008 0x0000b38c 69 597 -&gt; 711 section..debug_S_70 0x0000b7e2 8 164 -&gt; 166 sym.__unwindfunclet__Resynchronize_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEH_Z_0 0x0000b890 76 1581 -&gt; 1597 section..debug_S_73 0x0000bfd5 596 2248 -&gt; 2834 section..debug_S_75 0x0000cdaf 20 396 sym.__unwindfunclet__TruncatedFinal_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPAEI_Z_7 0x0000cf4c 13 177 sym._Update_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEI_Z 0x0000d061 82 625 -&gt; 706 section..debug_S_78 0x0000d53f 42 867 -&gt; 896 sym..text_x 0x0000d8b6 52 818 -&gt; 948 section..debug_S_83 0x0000dbe8 54 928 -&gt; 1018 section..debug_S_85 0x0000df9c 55 1312 -&gt; 1363 section..debug_S_87 0x0000e4c6 26 685 -&gt; 727 section..debug_S_89 0x0000e787 11 165 -&gt; 168 fcn.0000e787 0x0000e8e9 1 11 sym.__Xran____String_val_U___Simple_types_D_std___std__SAXXZ 0x0000e908 19 352 -&gt; 382 section..debug_S_93 0x0000ea72 28 525 -&gt; 551 section..debug_S_95 0x0000ed10 3 31 sym._append___basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAEAAV12_QBD_Z 0x0000ed39 35 651 -&gt; 697 section..debug_S_97 0x0000efd8 66 968 -&gt; 1055 section..debug_S_99 0x0000f49e 3 30 sym._insert___basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAEAAV12_IABV12__Z 0x0000f4c6 34 954 -&gt; 976 section..debug_S_101 0x0000f8b2 15 381 -&gt; 395 section..debug_S_103 0x00010050 8 66 sym._reserve___basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAEXI_Z 0x000100a6 68 958 -&gt; 1063 section..debug_S_105 0x00010464 17 556 -&gt; 578 section..debug_S_107 0x0001069a 9 359 -&gt; 360 section..debug_S_109 0x00004100 6 101 sym.__ehhandler_____HDU__char_traits_D_std__V__allocator_D_1__std__YA_AV__basic_string_DU__char_traits_D_std__V__allocator_D_2__0 0x00010808 1 57 sym.__ehfuncinfo___0Exception_CryptoPP__QAE_W4ErrorType_01_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std___Z 0x00010848 1 57 sym.__ehfuncinfo___0Exception_CryptoPP__QAE_ABV01__Z 0x00010888 1 57 sym.__ehfuncinfo_____HDU__char_traits_D_std__V__allocator_D_1__std__YA_AV__basic_string_DU__char_traits_D_std__V__allocator_D_2 0x000108d0 1 67 fcn.000108d0 0x00010932 1 87 sym.__ehfuncinfo___0BadState_AuthenticatedSymmetricCipher_CryptoPP__QAE_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2 0x00010990 1 57 sym.__ehfuncinfo__Resynchronize_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEH_Z 0x000109d0 1 57 sym.__ehfuncinfo__Update_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEI_Z 0x00010a28 1 122 sym.__ehfuncinfo__ProcessData_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPAEPBEI_Z 0x00010c40 1 12 sym.__CT___R0_AVexception_std___8__0exception_std__QAE_ABV01__Z12 0x00010c70 5 149 sym.___C__02LMMGGCAJ__3_5 0x00010d53 1 12 sym.__CT___R0_AVException_CryptoPP___8__0Exception_CryptoPP__QAE_ABV01__Z40 0x00010d83 22 421 -&gt; 456 section..xdata_x_131 0x00010f4b 1 122 sym.___R4InvalidArgument_CryptoPP__6B 0x00010fe8 24 285 -&gt; 312 sym.___R4BadState_AuthenticatedSymmetricCipher_CryptoPP__6B 0x0001111e 1 12 sym..xdata_x 0x00011292 72 551 -&gt; 631 section..debug_S_169 0x00000e92 3 78 fcn.00000e92 </code></pre> <p>I m using Python for extraction but some of these functions are not real function for example: section..debug_S_105</p> <p>What do I have to do in detail to avoid the data garbage and just find real functions (like in source code)? Or did I compile the source code wrong? </p>
Extracting functions of .obj file (compiled by myself with Visual Studio 19) --> extracts wrong data
|binary-analysis|c++|radare2|functions|
<p>one can read a pointer value <strong>using * symbol</strong><br> <strong>$$ is alias</strong> for current virtual seek<br> so *$$ will return the value stored at current seek</p> <p>you can execute the command and pass the result to seek like </p> <pre><code>s `*$$` </code></pre> <p>a simple example showing how to seek to an address stored in 3rd DWORD from current seek</p> <pre><code>[0x01012d6c]&gt; sentry0 [0x01012d6c]&gt; x/4xw 0x01012d6c 0xfffd4be8 0x68586aff 0x01012ee8 0xff99ebe8 .K...jXh........ [0x01012d6c]&gt; s `*$$+8` [0x01012ee8]&gt; </code></pre>
23224
2020-02-10T03:53:12.560
<p>Using <code>radare2</code>, I am reverse engineering a custom language interpreter. It stores compiled functions as a list of pointers to language primitives. I would like to <code>seek</code> to these locations, but typing in the hex addresses is very frustrating. I can't seem to find any syntax for saying "seek to the address stored at the current location".</p> <p>E.g., say I am looking at the following in visual mode:</p> <pre><code>; UNKNOWN XREFS from entry0 @ 0x400382, 0x400384 ; UNKNOWN XREF from entry0 @ +0x82 ;-- section..text: 0x004000b0 .qword 0x00000000004002f3 ; aav.0x004002f3 ; [01] -r-x section size 736 named .text 0x004000b8 .qword 0x0000000000000064 0x004000c0 .qword 0x0000000000400301 ; aav.0x00400301 0x004000c8 .qword 0x000000000040032e ; aav.0x0040032e 0x004000d0 .qword 0x000000000040030c ; aav.0x0040030c . . . </code></pre> <p>The "current location" is at <code>0x004000b0</code>, and it stores the value <code>0x4002f3</code>, which is where I'd like to seek. For now, I have to type <code>g</code> followed by reading and typing out, or selecting and pasting, the address <code>0x4002f3</code>.</p> <p>Is there some efficient way to say "seek to the value stored at <code>$$</code>"?</p>
Seek to value stored in memory in radare2
|radare2|
<p>You're showing x86 (32bit) shellcode, but are not compiling your program for that architecture, so <code>gcc</code> most likely creates an amd64 (64bit) executable instead. This can be fixed by adding the <code>-m32</code> switch:</p> <pre><code>gcc -g -Wall -fno-stack-protector -z execstack -m32 code.c -o code </code></pre> <p>You can verify this by running <code>file</code> on the resulting file:</p> <pre><code>code: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), […] </code></pre>
23225
2020-02-10T06:46:19.983
<p>I wrote a small program in assembly which is supposed to print "AAAA". It works fine when I run it directly, but when I run it as a shellcode in a c program, it doesn't work. Please help.</p> <p>Here is the assembly code: <a href="https://i.stack.imgur.com/3oQA2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3oQA2.png" alt="enter image description here"></a></p> <p>When I compile and execute the following code:</p> <pre><code>char shellcode[] = {0x31,0xc0,0xb0,0x04,0x31,0xdb,0xb3,0x01,0x68,0x41,0x41,0x41,0x41,0x89,0xe1,0x31,0xd2,0xb2,0x04,0xcd,0x80,0x31,0xc0,0xb0,0x01,0x31,0xdb,0xb3,0x01,0xcd,0x80}; int main(){ (*(void(*)())shellcode)(); return 0; } </code></pre> <p>Compiled as:</p> <pre><code>$gcc -g -Wall -fno-stack-protector -z execstack code.c -o code </code></pre> <p>Execution:</p> <pre><code>$./code $ </code></pre>
Shellcode not working correctly
|disassembly|assembly|shellcode|
<p>Visual Studio is inlining the function. You will need to tell VS to not do that:</p> <pre><code>__declspec(noinline) void someFunction() { printf("im scared world, i dont understand.\n"); } </code></pre>
23232
2020-02-11T15:37:14.693
<p>I made a simple program in C++ using Visual Studio 2019 to learn. When I open the file with Ghidra, it doesn't seem to detect my functions and I don't know what I'm doing wrong.</p> <p>My program is simple:</p> <pre><code>#include &lt;iostream&gt; void someFunction() { printf("im scared world, i dont understand.\n"); } int main() { std::cout &lt;&lt; "hello world" &lt;&lt; '\n'; someFunction(); system("pause"); return 0; } </code></pre> <p>Yet the main function looks like this in Ghidra:</p> <pre><code>int __cdecl _main(int _Argc,char **_Argv,char **_Env) { char cVar1; char *unaff_EBP; basic_ostream&lt;char,struct_std::char_traits&lt;char&gt;_&gt; *in_stack_fffffff8; cVar1 = (char)unaff_EBP; operator&lt;&lt;&lt;struct_std::char_traits&lt;char&gt;_&gt;(in_stack_fffffff8,unaff_EBP); operator&lt;&lt;&lt;struct_std::char_traits&lt;char&gt;_&gt;(in_stack_fffffff8,cVar1); /* Symbol Ref: No symbol: someFunction */ _printf("im scared world, i dont understand.\n"); system("pause"); return 0; } </code></pre> <p>As you can see, where my function should be, it instead shows</p> <pre><code>/* Symbol Ref: No symbol: someFunction */ </code></pre> <p>Why? What can I do to fix this?</p>
Ghidra can't see basic functions in my files?
|c++|ghidra|
<p>movsxd moves the dword by sign extending the dword into qword </p> <p>so for this example rdx will be eax+edx </p> <pre><code>C:\&gt;python -c "print( hex(0x26d1+0x40d)) 0x2ade </code></pre> <p>you can use some emulators like unicorn<br> or use a debugger and patch this instructions some place and loop<br> or compile a small source as below to get an understanding<br> (the code below sign extends a 16bit input to a 32bit output )<br> in your example a 32bit input is taken to output a 64bit<br> there is also an 8bit input and 16 bit output<br> movsxb(8in160ut),movsxw(16in320ut),movsxd (32in640ut) </p> <pre><code>#include &lt;stdio.h&gt; int main(void) { printf("movsxd demo\n"); signed short edx = 0x26d1; signed short eax = 0x40d; for (int i = 0; i &lt; 25; i++ ){ edx = edx + eax; printf("%x\n",edx); } } </code></pre> <p>compiled and executed you can see how and when it gets sign extended</p> <pre><code>:\&gt;cl /Zi /W4 /analyze /EHsc /nologo /Od movsxd.cpp /link /release movsxd.cpp :\&gt;movsxd.exe movsxd demo 2ade 2eeb 32f8 3705 3b12 3f1f 432c 4739 4b46 4f53 5360 576d 5b7a 5f87 6394 67a1 6bae 6fbb 73c8 77d5 7be2 7fef ffff83fc &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; ffff8809 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; ffff8c16 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; </code></pre> <p>just to show a simplified disassembly i refactored the code to eliminate superfluous print's, assignments , etc and compiled it with full optimizations and disassembled<br> code </p> <pre><code>#include &lt;stdio.h&gt; int main(void) { signed short edx = 0x26d1; for (int i = 0; i &lt; 25; i++ ){ edx = edx + 0x40d; printf("%x\n",edx); } } </code></pre> <p>disassembly see how word from si (16 bit of ESI)is sign extended to eax(32 bit)</p> <pre><code>:\&gt;cdb -c "uf movsxd!main;q" movsxd.exe |awk "/Reading/,/quit/" 0:000&gt; cdb: Reading initial command 'uf movsxd!main;q' movsxd!main: 01291000 56 push esi 01291001 57 push edi 01291002 bed1260000 mov esi,26D1h 01291007 bf19000000 mov edi,19h 0129100c 0f1f4000 nop dword ptr [eax] movsxd!main+0x10: 01291010 81c60d040000 add esi,40Dh 01291016 0fbfc6 movsx eax,si &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; when si will be &gt; 0x7fff (max signed short) eax will get sign extended. 01291019 50 push eax 0129101a 6890012d01 push offset movsxd!__xt_z+0x8 (012d0190) 0129101f e85c000000 call movsxd!printf (01291080) 01291024 83c408 add esp,8 01291027 83ef01 sub edi,1 0129102a 75e4 jne movsxd!main+0x10 (01291010) movsxd!main+0x2c: 0129102c 5f pop edi 0129102d 33c0 xor eax,eax 0129102f 5e pop esi 01291030 c3 ret quit: </code></pre>
23245
2020-02-13T23:35:47.023
<p>I've tried reading the documentation but the functionality of this instruction is still cloudy to me. For an example, I would like to know what is stored in RDX after these instructions:</p> <pre><code>mov edx, 0x26d1 mov eax, 0x40d add eax, edx movsxd rdx, eax </code></pre> <p>Personally, I think it is 0x0000000000002ade because I don't think the signed bit at bit position 31 was present in eax at the time. (If that makes any sense?) Any help would be appreciated and maybe an explanation that doesn't leave me confused would be awesome as well :) Thanks and have a good day!</p>
Help understanding MOVSXD
|assembly|x86-64|
<p>There was a project of using these files to <a href="https://yifan.lu/2015/12/29/cgen-for-ida-pro/" rel="nofollow noreferrer">create a processor module for IDA</a>, maybe you can reuse parts of it.</p>
23247
2020-02-14T11:02:39.020
<p>Is there a tool to automatically convert binutils cpu definitions (.cpu / .opc files) to sleigh for use in Ghidra? ... or do I need to hand craft a cpu definition for Synopsys DesignWare ARC 625D?</p>
Convert .cpu / .opc to sleigh
|ghidra|
<p>The keyspace for x is only <code>2**32</code>. This can be easily bruteforced. Also you can use something like <a href="https://github.com/Z3Prover/z3" rel="nofollow noreferrer">z3</a> a SAT solver to model the equations. For your given pair these were the possible 16 values for x</p> <pre><code>0x153f11fa, 0x953f11fa 0x24c66e44, 0xa4c66e44 0x3bcc14c8, 0xbbcc14c8 0x3c2918cb, 0xbc2918cb 0x477bb478, 0xc77bb478 0x662a1eac, 0xe62a1eac 0x71539c35, 0xf1539c35 0x76a55966, 0xf6a55966 </code></pre> <p>With an additional keypair the candidates can be boiled down to 2 values</p> <pre><code>xxxxxxxxxx:::0x01010101:0x02020202:0x03030303:0x08010101 0x3bcc14c8:::0xffaa5550:0x88cc8330:0x7766d660:0x87a95f90 0xbbcc14c8:::0xffaa5550:0x88cc8330:0x7766d660:0x87a95f90 </code></pre> <p>Both of these can be used interchangeably as the 31st bit is inconclusive.</p>
23256
2020-02-15T06:20:09.700
<p>I am trying to reverse a seed/key algorithm that has a constant value inside it. and there is different const value for different device that use this algorithm. i can give some sample from each device so i have seed/key of devices. the algorithm is :</p> <pre><code>int SeedKey_Algorithm(int seed){ // sample input: 0x01010101 for (int i = 0; i &lt; 0x23; i++) { if ((seed &amp; 0x80000000) == 0x80000000) { seed = ( x ^ seed); // x is constant value } seed = seed &lt;&lt; 1; } return seed; //out = 0xFFAA5550 } </code></pre> <p>then if when inject the 0x01010101 as input we get 0xFFAA5550 as output. so how i can find this constant value. is there any mathematics algorithm for find it? is it needed more sample for reverse this?</p> <p><strong>UPDATE</strong><br> so i check another device that work with this algorithm and i find 12 true value for 0x01010101.<br> <code>0x0d7c76ff, 0x1049164d, 0x37749eba, 0x6071e476, 0x6cced1e7, 0x7657a4aa, 0x8d7c76ff, 0x9049164d, 0xb7749eba, 0xe071e476, 0xecced1e7, 0xf657a4aa</code></p> <p>but for 0x02020202 i can't find any right value :(<br> is this possible? or I made a mistake?</p>
Seed/Key Constant Value
|debugging|
<ul> <li>Section information is not used at all when the kernel loads a program into memory to create its process image. In other words, execution in no way depends on section information. </li> <li>Stripping section information from a binary is not in and of itself necessarily an indicator of dangerous/criminal functionality, although it can serve to make analysis more difficult. </li> <li>According to VirusTotal, the example binary you linked to contains 29 sections, so I am not sure what that is supposed to be an example of. Perhaps one of the fields in the ELF header having to do with sections has been edited/corrupted to slow down automatic analysis, since section information cannot be displayed. <ul> <li>if the section header table is still present in the binary, the ELF header can be repaired so that this information is properly parsed. See <a href="https://binaryresearch.github.io/2020/01/15/Analyzing-ELF-Binaries-with-Malformed-Headers-Part-3-Solving-A-Corrupted-Keygenme.html" rel="nofollow noreferrer">here</a> for an example</li> <li>run <code>readelf -h</code> against the binary to see if the ELF header has been corrupted</li> </ul></li> <li>A number of tools can parse such a binary, including radare2, Cutter, IDA, and Ghidra </li> </ul>
23264
2020-02-15T23:01:11.860
<p>On VirusTotal, there are lots of ELF samples are <code>missing section headers</code> when using <code>file</code> command to see the info.</p> <p>Also, when using the Python <code>elftools</code> library to parse them, exceptions will be thrown.</p> <p>Can these kinds of ELF files still be executed or dangerous? If so, what's the best way to parse them?</p> <p>Example: <a href="https://www.virustotal.com/gui/file/7096d1deb8a097b25a74cb2b72009dc37430180b53725e1bec4d18be5856f139/detection" rel="nofollow noreferrer">https://www.virustotal.com/gui/file/7096d1deb8a097b25a74cb2b72009dc37430180b53725e1bec4d18be5856f139/detection</a> (This is not a good example as it's a ".so" file.)</p> <hr> <p>Add the real output:</p> <p>readelf -h:</p> <pre><code>ELF Header: Magic: 7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, big endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: IBM S/390 Version: 0x1 Entry point address: 0x403650 Start of program headers: 52 (bytes into file) Start of section headers: 1090000 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 8 Size of section headers: 40 (bytes) Number of section headers: 27 Section header string table index: 26 readelf: Error: Reading 0x438 bytes extends past end of file for section headers </code></pre> <p>readelf -l:</p> <pre><code>readelf: Error: Reading 0x438 bytes extends past end of file for section headers Elf file type is EXEC (Executable file) Entry point 0x403650 There are 8 program headers, starting at offset 52 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align PHDR 0x000034 0x00400034 0x00400034 0x00100 0x00100 R E 0x4 INTERP 0x000134 0x00400134 0x00400134 0x0000d 0x0000d R 0x1 [Requesting program interpreter: /lib/ld.so.1] LOAD 0x000000 0x00400000 0x00400000 0xd7c70 0xd7c70 R E 0x1000 LOAD 0x0d7c70 0x004d8c70 0x004d8c70 0x2da34 0x3167c RW 0x1000 DYNAMIC 0x1052a8 0x005062a8 0x005062a8 0x000e0 0x000e0 RW 0x4 NOTE 0x000144 0x00400144 0x00400144 0x00020 0x00020 R 0x4 GNU_EH_FRAME 0x0d7b7c 0x004d7b7c 0x004d7b7c 0x0002c 0x0002c R 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4 </code></pre>
Can "missing section headers" ELF files still be executed/dangerous?
|elf|file-format|executable|
<p>for an <strong>array x[]</strong> whose <strong>count is n</strong></p> <p>the series for v3 without the mod() will be </p> <p>n * (1 + x[0]) + (n-1) * x[1] + (n-2) * x[2] + (n-3) * x[3] + .... (n-r) * x[r] +...+ x[n] </p> <p>the series for v2 without the mod() will be</p> <p>1+x[0]+x[1]+x[2]+....x[r]+...x[n]</p> <p>assuming "secret" is passed as input<br> then hash will be 0xf72efd78</p> <p>redone in python</p> <pre><code>input = "secret" l = len(input) v2 = 0 v3 = 1 for i in range(0,l,1): v3 = (ord(input[i]) + v3) v2 = v3 + v2 print(hex(v2),hex(v3)) print ("hash for input %s = %08x" %(input,(~(v2 &lt;&lt; 16 | v3)) &amp; 0xffffffff)) </code></pre> <p>result </p> <pre><code>0x74 0x74 0x14d 0xd9 0x289 0x13c conforming the series for v2 &gt;&gt;&gt; hex( 3 * (1 + ord("secret"[0])) + 2 * ord("secret"[1]) + 1 * ord("secret"[2])) '0x289' 0x437 0x1ae 0x64a 0x213 0x8d1 0x287 hash for input secret = f72efd78 </code></pre>
23297
2020-02-19T18:19:21.767
<p>What is the hash? Generated from ida pro</p> <pre><code>int __fastcall hash(_BYTE *a1) { _BYTE *v1; // r4@1 int v2; // r5@1 int v3; // r6@1 v1 = a1; v2 = 0; v3 = 1; while ( *v1 ) { v3 = (*v1 + v3) % 51407; v2 = (v3 + v2) % 51407; ++v1; } return ~(v3 | (v2 &lt;&lt; 16)); } </code></pre>
Hash from pseudocode
|ida|c++|c|
<p>No, it doesn’t support ARM files.</p> <p>From <a href="https://www.hex-rays.com/products/ida/support/download_freeware/" rel="nofollow noreferrer">the description</a>:</p> <blockquote> <p>The freeware version of IDA v7.0 comes with the following limitations:</p> <p>• no commercial use is allowed</p> <p>• lacks all features introduced in IDA &gt; v7.0</p> <p>• <strong>lacks support for many processors</strong>, file formats, etc…</p> <p>• comes without technical support</p> </blockquote>
23298
2020-02-19T19:32:03.210
<p>I have a .so file from an android app, and I want to disassemble it with IDA. However I get the error: <code>The processor type 'arm' is not included in the installed version of IDA.</code></p> <p>IDA Version: Freeware 7.0<br> OS: Windows 10</p> <p>Can the freeware 7.0 just not disassemble arm files? If not, what is a suitable alternative that actually works properly and displays a nice function table etc.? Thanks!</p>
IDA Freeware 7.0 disassemble ARM .so file
|ida|arm|shared-object|
<p>There are a couple of options for this.</p> <ul> <li>Use <a href="https://github.com/pwndbg/pwndbg" rel="noreferrer">pwndbg</a> or <a href="https://github.com/hugsy/gef" rel="noreferrer">gef</a>. They have a command called <code>got</code> which looks like this</li> </ul> <pre><code>gef➤ got GOT protection: Partial RelRO | GOT functions: 4 [0x555555755018] free@GLIBC_2.2.5 → 0x555555554606 [0x555555755020] puts@GLIBC_2.2.5 → 0x555555554616 [0x555555755028] malloc@GLIBC_2.2.5 → 0x555555554626 [0x555555755030] sprintf@GLIBC_2.2.5 → 0x555555554636 </code></pre> <pre><code>pwndbg&gt; got GOT protection: Partial RELRO | GOT functions: 4 [0x555555755018] free@GLIBC_2.2.5 -&gt; 0x555555554606 (free@plt+6) ◂— push 0 /* 'h' */ [0x555555755020] puts@GLIBC_2.2.5 -&gt; 0x555555554616 (puts@plt+6) ◂— push 1 [0x555555755028] malloc@GLIBC_2.2.5 -&gt; 0x555555554626 (malloc@plt+6) ◂— push 2 [0x555555755030] sprintf@GLIBC_2.2.5 -&gt; 0x555555554636 (sprintf@plt+6) ◂— push 3 </code></pre> <ul> <li>According to <a href="https://github.com/pwndbg/pwndbg/blob/cc0c90a4a4599ca6f0470157db5fc78c2708a904/pwndbg/wrappers/readelf.py#L15" rel="noreferrer">their</a> <a href="https://github.com/hugsy/gef/blob/7bd407a1bb90e34730351715d323bc905275859a/gef.py#L8745" rel="noreferrer">sources</a> both use <code>readelf</code> as such to display this information</li> </ul> <pre><code>$ readelf --relocs ll Relocation section '.rela.dyn' at offset 0x4a0 contains 9 entries: Offset Info Type Sym. Value Sym. Name + Addend 000000200dd8 000000000008 R_X86_64_RELATIVE 750 000000200de0 000000000008 R_X86_64_RELATIVE 710 000000201040 000000000008 R_X86_64_RELATIVE 201040 000000200fd0 000200000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_deregisterTMClone + 0 000000200fd8 000400000006 R_X86_64_GLOB_DAT 0000000000000000 __libc_start_main@GLIBC_2.2.5 + 0 000000200fe0 000500000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0 000000200fe8 000700000006 R_X86_64_GLOB_DAT 0000000000000000 _Jv_RegisterClasses + 0 000000200ff0 000900000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_registerTMCloneTa + 0 000000200ff8 000a00000006 R_X86_64_GLOB_DAT 0000000000000000 __cxa_finalize@GLIBC_2.2.5 + 0 Relocation section '.rela.plt' at offset 0x578 contains 4 entries: Offset Info Type Sym. Value Sym. Name + Addend 000000201018 000100000007 R_X86_64_JUMP_SLO 0000000000000000 free@GLIBC_2.2.5 + 0 000000201020 000300000007 R_X86_64_JUMP_SLO 0000000000000000 puts@GLIBC_2.2.5 + 0 000000201028 000600000007 R_X86_64_JUMP_SLO 0000000000000000 malloc@GLIBC_2.2.5 + 0 000000201030 000800000007 R_X86_64_JUMP_SLO 0000000000000000 sprintf@GLIBC_2.2.5 + 0 </code></pre> <p>And then use this output to dump GOT while debugging.</p> <ul> <li>Another method is to use <code>plt</code> symbols to resolve <code>got</code></li> </ul> <pre><code>pwndbg&gt; disass 'puts@plt' Dump of assembler code for function puts@plt: 0x0000555555554610 &lt;+0&gt;: jmp QWORD PTR [rip+0x200a0a] # 0x555555755020 0x0000555555554616 &lt;+6&gt;: push 0x1 0x000055555555461b &lt;+11&gt;: jmp 0x5555555545f0 End of assembler dump. pwndbg&gt; tele 0x555555755020 00:0000│ 0x555555755020 (_GLOBAL_OFFSET_TABLE_+32) —▸ 0x7ffff7aa2f90 (puts) ◂— push r13 01:0008│ 0x555555755028 (_GLOBAL_OFFSET_TABLE_+40) —▸ 0x7ffff7ab4f10 (malloc) ◂— push rbp 02:0010│ 0x555555755030 (_GLOBAL_OFFSET_TABLE_+48) —▸ 0x7ffff7a892d0 (sprintf) ◂— sub rsp, 0xd8 03:0018│ 0x555555755038 (data_start) ◂— 0x0 04:0020│ 0x555555755040 (__dso_handle) ◂— 0x555555755040 /* '@PuUUU' */ 05:0028│ 0x555555755048 (completed) ◂— 0x0 ... ↓ pwndbg&gt; print puts $13 = {&lt;text variable, no debug info&gt;} 0x7ffff7aa2f90 &lt;_IO_puts&gt; </code></pre>
23311
2020-02-21T01:01:35.990
<p>I want to see how the plt stubs are being resolved at run time when lazy linking is used and how the GOT is changed along the way. How can I dump the GOT with gdb?</p>
Dumping the GOT with gdb at run time
|binary-analysis|gdb|elf|plt|got|
<p>I was working on this this weekend. Turns out it's pretty straight-forward. Simple list of contiguous files. Just copies files when they change, and marks the allocation-table entries as dead, for later collection. </p> <p>The following is incomplete, but it should let you tweak and special-case your way through a specific MFS partition. I've tried to document in comments where I've made large assumptions.</p> <p><strong>EDIT: There do seem to be metadata in the data.</strong> E.g., when looking at the content of UKS, the copy in the SCA partition is clearly <code>0E f4 00 00</code> whereas in MFS, the data there is <code>80 06 0e f4 00 00</code>, so it looks like there's <em>leading</em> metadata. </p> <p><strong>EDIT 2: Figured out the metadata.</strong> It gives a much better method for deterministically identifying files by number within a block than the method I devised without it. Updated the code with a description and a rather complicated state-machine for successfully processing the metadata.</p> <pre><code>import sys #litte-endian integer readers def read_leuint8(file): data = file.read(1) return data[0] def read_leuint16(file): data = file.read(2) return data[0] | (data[1] &lt;&lt; 8) def read_leuint24(file): data = file.read(3) return data[0] | (data[1] &lt;&lt; 8) | (data[2] &lt;&lt; 16) def read_leuint32(file): data = file.read(4) return data[0] | (data[1] &lt;&lt; 8) | (data[2] &lt;&lt; 16) | (data[3] &lt;&lt; 24) class MEFileSystemFileMetadataStateMachine: """ MEFileSystemFileMetadata: Files in MFS have internal metadata entries. Each file begins with a metadata record, observed values are: 0xa# &lt;bytes ahead until next metadata&gt; &lt;0x01&gt; &lt;next meta block num&gt; &lt;0x00&gt; 0xb# &lt;blocks ahead until next metadata&gt; &lt;0x01&gt; &lt;next meta block num&gt; &lt;0x00&gt; 0x8# &lt;bytes remaining in file (including this metadata)&gt; where # -- is the file number within the block. This is the target for the fno field of the allocation table entry. &lt;bytes ahead...&gt; -- the number of bytes to move ahead to find the next metadata record (including this metadata). &lt;next meta block...&gt;-- the 0x100-byte block number where the next metadata record is to be found. This value should be looked up through the data-page's block-indirection table. &lt;blocks ahead...&gt; -- the number of 0x100 byte blocks to move ahead to find the next metadata record (including this metadata). &lt;bytes remaining...&gt;-- pretty straight-forward. So, 0x8# metadata are file-end records; 0xa# are short-range references; and 0xb# are longer range references. This metadata chain provides unamiguous file numbers within the blocks, and since they're put at the block start of any block that contains a file-start, it's easy to pick up from an allocation table reference. Note: 0x8# records don't point to the next metadata block, so we may have to consume file-end padding (0xff until the next multiple of 0x10) if we get an intermediate 0x8# metadata while searching for our target file. """ STATE_NEED_META = 0 STATE_NEED_SKIP_DATA = 1 STATE_NEED_FILE_DATA = 2 STATE_COMPLETE = 3 def __init__(self, file_no, file_len): self.file_no = file_no self.state = MEFileSystemFileMetadataStateMachine.STATE_NEED_META self.bytes_needed = 1 self.byte_offset = 0 self.cur_meta = bytearray(5) self.file_data = bytearray(file_len) self.file_filled = 0 self.found_fileno = False self.work_buf = self.cur_meta def is_complete(self): return self.state == self.STATE_COMPLETE def get_file_data(self): return self.file_data def get_bytes_needed(self): return self.bytes_needed #returns the number of bytes consumed def add_bytes(self, bytes, start_index, data_len=None, log_file = None): """ supplies data to satisfy the state-machine's need for data as reported via get_bytes_needed(). bytes -- the buffer containing the bytes to be fed in start_index -- the start location of the bytes within the buffer data_len -- number of bytes in the array, starting at start_index. if None, then len(bytes) - start_index is assumed """ #shuffling data from potentially multiple calls to fill the data request from the #state machine (get_bytes_needed) data_len = len(bytes) - start_index if data_len is None else data_len if data_len == 0: return 0 # nothing to do #take the min of what's available and what we need to_copy = data_len if data_len &lt; self.bytes_needed else self.bytes_needed if self.work_buf: self.work_buf[self.byte_offset:(self.byte_offset+to_copy)] = bytes[start_index:(start_index+to_copy)] self.byte_offset = self.byte_offset + to_copy self.bytes_needed = self.bytes_needed - to_copy #if we don't have enough to process, return so they can feed more if self.bytes_needed &gt; 0: return to_copy #we only make it this far once we've got the full bytes_needed data meta_type = self.cur_meta[0] &amp; 0xf0 if self.state == self.STATE_NEED_META: if self.byte_offset == 1: if meta_type in [0xa0, 0xb0]: self.bytes_needed = 4 else: self.bytes_needed = 1 else: #Have we found the file number we seek yet? if self.found_fileno or (self.file_no == self.cur_meta[0] &amp; 0x0f): self.found_fileno = True self.state = self.STATE_NEED_FILE_DATA self.work_buf = self.file_data self.byte_offset = self.file_filled else: self.state = self.STATE_NEED_SKIP_DATA self.work_buf = None self.byte_offset = None #determine the data required based on metadata type, and whether we're #skipping (so need to eat EOF padding on type 0x8# entries) or whether #we're copying out file data. if meta_type == 0x80: if self.state == self.STATE_NEED_SKIP_DATA: #if we're skipping a 0x8# entry, we need to eat EOF padding too padding = (0x10 - (self.cur_meta[1] &amp; 0xf)) &amp; 0xf self.bytes_needed = padding + self.cur_meta[1] - 2 #remove header len, too else: self.bytes_needed = self.cur_meta[1] - 2 #remove header len elif meta_type == 0xa0: self.bytes_needed = self.cur_meta[1] - 5 #remove header len elif meta_type == 0xb0: self.bytes_needed = self.cur_meta[1] * 0x100 - 5 #remove header len else: if log_file: log_file.write("That's not a metadata type I've seen before...: 0x%02x\n" % self.cur_meta[0]) return None elif self.state == self.STATE_NEED_SKIP_DATA: #recall: this is the state just *completed* self.state = self.STATE_NEED_META self.work_buf = self.cur_meta self.byte_offset = 0 self.bytes_needed = 1 elif self.state == self.STATE_NEED_FILE_DATA: #recall: this is the state just *completed* self.file_filled = self.byte_offset self.state = self.STATE_NEED_META self.work_buf = self.cur_meta self.byte_offset = 0 if meta_type == 0x80: #just completed a file-end record...we're done. self.bytes_needed = 0 self.state = self.STATE_COMPLETE elif meta_type in [0xa0, 0xb0]: self.bytes_needed = 1 else: if log_file: log_file.write("That's not a metadata type I've seen before...: 0x%02x\n" % self.cur_meta[0]) return None elif self.state == self.STATE_COMPLETE: #can't leave this state pass else: if log_file: log_file.write("Bad state-machine state: %d\n" % self.state) #recurse to consume as much as we can, for easier calling convention if to_copy &lt; data_len: return to_copy + add_bytes(bytes, start_index+to_copy, data_len-to_copy) #else, return what we consumed return to_copy def read_me_fs_file(file_no, file_len, me_file, log_file = sys.stdout): sm = MEFileSystemFileMetadataStateMachine(file_no, file_len) while not sm.is_complete(): res = sm.add_bytes( bytes=me_file.read(sm.get_bytes_needed()), start_index=0, data_len=None, #shorthand for len(bytes)-start_index log_file=log_file) if not res: log_file.write("Aborting file read.\n") break return sm.get_file_data() class MEFileSystemDataHeader: """ Data Page Header: (Top of a 0x4000-byte data page in the MFS) 0 1 2 3 4 5 6 7 8 9 a b c d e f +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 00 | pgno| pgflags | 0x00| 0x00| 0x00| 0x00| mystery bits | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 10 | freed_flags... | +-----------------------------------------------------------------------------------------------+ ... | ... | +-----------------------------------------------------------------------------------------------+ 80 | ... | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 90 | block indirection table... | +-----------------------------------------------------------------------------------------------+ ... | ... | +-----------------------------------------------------------------------------------------------+ c0 | ... | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ d0+| (file data follows) | +-----------------------------------------------------------------------------------------------+ pgno -- page identifier within the MFS. All MFS page headers have this field, be they AT or Data. pgflags -- have seen 0x78 0xfe 0xff for AT header. Data pages have had this or 0x78 0xfc 0xff. (zeros) -- a useless value for flash...must be part of the signature of the header? Or reserved region for later version of the format. myst_bits -- TBD freed_flags-- each bit marks whether a written 0x10-byte chunk is no longer required. Bits exist for the header chunks, as well as the chunks for file data. lsb of the first byte corresponds to the first chunk of the header. 0=freed. blk_itab -- translates ATFileEntry's okey value into a block offset within the data page. offset = blk_itab[okey] * 0x100. This is the location from which to begin the search. Note that an offset of 0 must still respect that the page header consumes bytes [0x00, 0xd0) for the search. (filedata) -- File are padded with 0xff at the end. Note files have internal metadata. See routines above. """ def __init__(self, page_no, flags, bytes_00000000, myst_bits, freed_flags, blk_itab): self.page_no = page_no self.flags = flags self.zeros_good = bytes_00000000 == b'\x00\x00\x00\x00' self.myst_bits = myst_bits self.freed_flags = freed_flags self.blk_itab = blk_itab def debug_print(self, log = sys.stdout): log.write("Debug Print of MEFileSystemDataHeader %x:\n" % id(self)) if self.page_no != 0xff: log.write(" page no: 0x%x\n" % self.page_no) log.write(" flags: 0x%06x\n" % self.flags) log.write(" zeros good: %s\n" % str(self.zeros_good)) log.write(" mystery bits: %s\n" % " ".join("%02x"%x for x in self.myst_bits)) log.write(" freed_flags: %s\n" % "".join("%02x"%x for x in self.freed_flags)) log.write(" block ind. tab.: [%s]\n" % " ".join("%02x"%x for x in self.blk_itab)) else: log.write(" (empty)\n") class MEFileSystemATEntry: """ Allocation Table Entry: 0 1 2 3 4 5 6 7 8 9 a +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 00 |state| flgs| identifier | type| filelen | pgid| okey| fno | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ state -- status of the entry: 0xdc=present; 0xc8=overwritten(i.e., there will be another entry below) flags -- has value 0xf0 in every example...so hard to tell. identifier -- 3-byte identifier...seem to be a preference for ASCII, but there are counterexamples type -- no idea...maybe permissions? Observed values: 0x00, 0x0a, 0x0c, 0x0d, 0x0e, 0x18, 0x1a filelen -- 16-bit, little endian. actual content seems to be a few bytes more...might just be pollution of the structures used to write the file. pgid -- the pgno for the MEFileSystemDataHeader that holds the data. The ATHeader is numbered 0, each data page seems to get sequentially numbered in my examples, though that could change with more use. 0xff indicates "not yet used / nonumber assigned" --- a fact that hints page numbers aren't guaranteed to be sequentially okey -- key for indexing the block_indirection table of the MEFileSystemDataHeader holding this file's content, to find the right 0x100 byte block from which to start the file search according to the 'fno' field. fno -- file number within the block-offset determined from okey. This is to be looked up using the metadata *within* the file data of the data pages. See MEFileSystemFileMetadataStateMachine above """ def __init__(self, state, flags, identifier, type, filelen, pgid, okey, fno): self.state = state self.flags = flags self.identifier = identifier self.type = type self.filelen = filelen self.pgid = pgid self.okey = okey self.fno = fno def debug_print(self, log = sys.stdout): log.write("%15s len=0x%04x [pg=0x%02x k=0x%02x f=0x%02x] ty=0x%02x st=0x%02x, fg=0x%02x" % (str(self.identifier), self.filelen, self.pgid, self.okey, self.fno, self.type, self.state, self.flags)) class MEFileSystemATHeader: """ Allocation Table Header: 0 1 2 3 4 5 6 7 8 9 a b c d e f +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 00 | pgno| flags | 0x00| 0x00| 0x00| 0x00|"MFS\0" |bitfields? | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 10 | bitfields? | +-----+-----+-----+-----+ pgno -- page identifier within the MFS. All MFS page headers have this field, be they AT or Data. flags -- have seen 0x78 0xfe 0xff for AT header. Data pages have had this or 0x78 0xfc 0xff. (zeros) -- a useless value for flash...must be part of the signature of the header? Or reserved region for later version of the format. "MFS\0" -- ASCIIZ signature for the MFS AT Header bitfields -- 64 bits of apparent bitfields """ max_files = int((0x4000 - 0x14) / 11) #page size, less the header, divided by file entry size def __init__(self, page_no, flags, bytes_00000000, sig, bitfields): self.page_no = page_no self.flags = flags self.zeros_good = bytes_00000000 == b'\x00\x00\x00\x00' self.sig_good = sig == b'MFS\x00' self.bitfields = bitfields def debug_print(self, log = sys.stdout): log.write("Debug Print of MEFileSystemATHeader %x:\n" % id(self)) log.write(" page no: 0x%x\n" % self.page_no) log.write(" flags: 0x%06x\n" % self.flags) log.write(" zeros good: %s\n" % str(self.zeros_good)) log.write(" sig good: %s\n" % str(self.sig_good)) log.write(" bitfields: %s\n" % " ".join("%02x"%x for x in self.bitfields)) class MEFileSystemAT: """ Allocation Table (a 0x4000-byte page in the MFS): 0 1 2 3 4 5 6 7 8 9 a b c d e f +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 00 | Allocation Table Header... | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 10 |... | File Entry |FE...| +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ ...|... | +-----------------------------------------------------------------------------------+-----+-----+ 3fe0|... |File Ent...| +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ 3ff0|... |Padding | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ """ def __init__(self, header, entry_list): self.header = header self.entry_list = entry_list def debug_print(self, log = sys.stdout): log.write("Debug Print of MEFileSystemAT %x:\n" % id(self)) self.header.debug_print(log) log.write("File entries:\n") for ent in self.entry_list: if(ent): log.write(" ") ent.debug_print(log) log.write("\n") class MEFileSystem: """ MFS Partition: (Making the assumption the AT is the first page) +------------------------------------+ 0000 | Allocation Table | +------------------------------------+ 4000 | Data Page | +------------------------------------+ 8000 | Data Page | +------------------------------------+ c000 | Data Page | +------------------------------------+ ... |... | +------------------------------------+ """ def __init__(self, allocation_table, data_page_list): self.allocation_table = allocation_table self.data_page_list = data_page_list def debug_print(self, log = sys.stdout): log.write("Debug Print of MEFileSystem %x:\n" % id(self)) self.allocation_table.debug_print(log) for page in self.data_page_list: if(page): page.debug_print(log) else: log.write("(Not parsed)\n") def parse_me_fs_at_entry(me_file, log_file = sys.stdout): return MEFileSystemATEntry( state = read_leuint8(me_file), flags = read_leuint8(me_file), identifier = me_file.read(3), type = read_leuint8(me_file), filelen = read_leuint16(me_file), pgid = read_leuint8(me_file), okey = read_leuint8(me_file), fno = read_leuint8(me_file)) def parse_me_fs_at_header(me_file, log_file = sys.stdout): return MEFileSystemATHeader( page_no = read_leuint8(me_file), flags = read_leuint24(me_file), bytes_00000000 = me_file.read(4), sig = me_file.read(4), bitfields = me_file.read(8)) def parse_me_fs_at(me_file, log_file = sys.stdout): hdr = parse_me_fs_at_header(me_file, log_file) entry_list = [None] * MEFileSystemATHeader.max_files for i in range(MEFileSystemATHeader.max_files): ent = parse_me_fs_at_entry(me_file, log_file) if ent.state == 0xff: break entry_list[i] = ent return MEFileSystemAT(hdr, entry_list) def parse_me_fs_data_header(me_file, log_file = sys.stdout): return MEFileSystemDataHeader( page_no = read_leuint8(me_file), flags = read_leuint24(me_file), bytes_00000000 = me_file.read(4), myst_bits = me_file.read(0x8), freed_flags = me_file.read(0x80), blk_itab = me_file.read(0x40)) def parse_me_fs(length, me_file, log_file = sys.stdout): """ ARGS: length -- length in bytes of the ME partition holding the MFS/MFSB data me_file -- a file handle whose present position is the start of the MFS(B) partition log_file -- if there is diagnostic output, put it here RETURNS: an MEFileSystem instance populated with the allocation table and data-page headers """ total_pages = int(length/0x4000) start_offset = me_file.tell() #NOTE: I'm presuming the allocation table is the first page... #that might not be reliable... at = parse_me_fs_at(me_file, log_file) data_pages = [None] * (total_pages-1) for page in range(0, total_pages-1): me_file.seek(start_offset + 0x4000 * (page+1)) data_pages[page] = parse_me_fs_data_header(me_file, log_file) return MEFileSystem( allocation_table=at, data_page_list = data_pages) def get_mfs_file(mefs, me_file, mfs_file_offset, id, log_file = sys.stdout): """ Example of how to use the MEFileSystem structures to retrieve MFS and MFSB files. ARGS: mefs -- a MEFileSystem instance parsed from mfs_data me_file -- a filehandle containing the ME image mfs_file_offset -- the file offset within me_file where the MFS partition begins id -- a 3-byte byte array with the file identifier log -- if there is diagnostic output, put it here RETURNS: an array containing [state, The data from the corresponding file]. else None if the file identifier does not exist within the data. Example driver, given the known offset and size for a MFS partition: MFS_OFFSET = 0x64000 #typical location MFS_LENGTH = 0x40000 #typical size spi_image_file.seek(MFS_OFFSET) mefs = parse_me_fs(MFS_LENGTH, spi_image_file) result_tuple = get_mfs_file(mefs, spi_image_file, MFS_OFFSET, b'UKS') if result_tuple: print("State: %x, data: %s\n" % tuple(result_tuple)) """ #Find the file identifer in the Allocation Table best_ent = None for ent in mefs.allocation_table.entry_list: if ent and ent.identifier == id: best_ent = ent if ent.state == 0xdc: break; # got a current entry log.write("Error: found an item w/ state %02x...continuing\n" % ent.state) #if found, lookup which data page matches the entry's pgid value if best_ent: page_found = False for list_idx in range(len(mefs.data_page_list)): page = mefs.data_page_list[list_idx] if page.page_no == best_ent.pgid: page_found = True #we found the right data page, so start the file search search_start = page.blk_itab[best_ent.okey] * 0x100 #In the following lines: # The value d0 is to skip over the datapage header if we're in the first block # # The multiple of 0x4000 selects the data offset that goes with list_idx # since the parsed data-page list is in the same order as found in the file. # # Because mefs.data_page_list doesn't include the allocation table page, we +1 # to the index before multiplying. The result is a set of offsets into the MFS data # bounding the file search ## search_off = 0x4000 * (list_idx+1) + (0xd0 if search_start == 0 else search_start) me_file.seek(mfs_file_offset + search_off) data = read_me_fs_file(best_ent.fno, best_ent.filelen, me_file, log_file) if data: return [best_ent.state, data] return None if __name__ == "__main__": with open("image.bin", "rb") as spi_image_file: MFS_OFFSET = 0x64000 #typical location MFS_LENGTH = 0x40000 #typical size spi_image_file.seek(MFS_OFFSET) mefs = parse_me_fs(MFS_LENGTH, spi_image_file) #Dump the allocation table mefs.allocation_table.debug_print() print("") first_file = mefs.allocation_table.entry_list[0].identifier print("looking up the first file (%s):" % first_file) result_tuple = get_mfs_file(mefs, spi_image_file, MFS_OFFSET, first_file) if result_tuple: print("State: %x, data: %s\n" % tuple(result_tuple)) </code></pre> <p>Oh, you can dump the file list with: <code>mefs.allocation_table.debug_print()</code></p> <p>E.g.,</p> <pre><code> b'UKS' len=0x0004 [pg=0x01 k=0x00 f=0x00] ty=0x0a st=0xdc, fg=0xf0 b'LRT' len=0x01c0 [pg=0x01 k=0x00 f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'MIA' len=0x0003 [pg=0x01 k=0x02 f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'BLV' len=0x0004 [pg=0x01 k=0x02 f=0x02] ty=0x0a st=0xdc, fg=0xf0 b'SDV' len=0x00ff [pg=0x01 k=0x02 f=0x03] ty=0x0a st=0xdc, fg=0xf0 b'ICP' len=0x0042 [pg=0x01 k=0x03 f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'\x00NP' len=0x0001 [pg=0x01 k=0x04 f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'PPN' len=0x0042 [pg=0x01 k=0x04 f=0x02] ty=0x0e st=0xdc, fg=0xf0 b'SCO' len=0x00af [pg=0x01 k=0x04 f=0x03] ty=0x0a st=0xdc, fg=0xf0 b'PCO' len=0x0a24 [pg=0x01 k=0x05 f=0x01] ty=0x0a st=0xdc, fg=0xf0 b'GFC' len=0x0004 [pg=0x01 k=0x07 f=0x01] ty=0x18 st=0xdc, fg=0xf0 b'YHP' len=0x06fe [pg=0x01 k=0x07 f=0x02] ty=0x0a st=0xdc, fg=0xf0 b'FCP' len=0x0002 [pg=0x01 k=0x09 f=0x01] ty=0x0b st=0xdc, fg=0xf0 b'PPR' len=0x0001 [pg=0x01 k=0x09 f=0x02] ty=0x0b st=0xdc, fg=0xf0 b'TCM' len=0x0005 [pg=0x01 k=0x09 f=0x03] ty=0x10 st=0xdc, fg=0xf0 b'BHM' len=0x0004 [pg=0x01 k=0x09 f=0x04] ty=0x10 st=0xdc, fg=0xf0 b'GCN' len=0x0018 [pg=0x01 k=0x09 f=0x05] ty=0x0e st=0xdc, fg=0xf0 b'CSM' len=0x000f [pg=0x01 k=0x0a f=0x00] ty=0x0e st=0xdc, fg=0xf0 b'\x00HS' len=0x0127 [pg=0x01 k=0x0a f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'\x01HS' len=0x0127 [pg=0x01 k=0x0b f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'\x02HS' len=0x0127 [pg=0x01 k=0x0c f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'\x03HS' len=0x0127 [pg=0x01 k=0x0d f=0x01] ty=0x0e st=0xdc, fg=0xf0 b'PCF' len=0x0010 [pg=0x01 k=0x0e f=0x01] ty=0x0e st=0xdc, fg=0xf0 ... </code></pre>
23324
2020-02-23T07:46:39.153
<ol> <li>What is the purpose of partitions <strong>EFFS</strong> and <strong>FCRS</strong> on systems with Intel ME 8.x?</li> <li>Is it currently possible to parse data in <strong>EFFS</strong> partition on a ME image?</li> </ol> <p>I hope anyone can help, there is so little information about this available.</p> <p>Thanks.</p>
Intel ME partitions EFFS and FCRS?
|firmware|intel|
<p>The following script shows hows to create a structure and set its field to Big Endian byte order using the Ghidra Python API.</p> <pre><code>from ghidra.program.model.data import DataTypeConflictHandler from ghidra.program.model.data import EndianSettingsDefinition from ghidra.app.util.cparser.C import CParser mystruct_txt = """ struct mystruct{ uint32_t field1; uint32_t field2; };""" # Get Data Type Manager data_type_manager = currentProgram.getDataTypeManager() # Create CParser parser = CParser(data_type_manager) # Parse structure parsed_datatype = parser.parse(mystruct_txt) # Add parsed type to data type manager datatype = data_type_manager.addDataType(parsed_datatype, DataTypeConflictHandler.DEFAULT_HANDLER) # Extract the first structure member i.e. mystruct.field1 field1 = datatype.components[0] # Get Default Settings field1_settings = field1.getDefaultSettings() # Set endianess to big field1_settings.setLong('endian', EndianSettingsDefinition.BIG) </code></pre> <p>If you have already created the structure earlier (using the editor or otherwise) you can omit the part where the structure is created and use <a href="https://ghidra.re/ghidra_docs/api/ghidra/program/database/data/DataTypeManagerDB.html#getDataType(java.lang.String)" rel="noreferrer"><code>getDataType</code></a> to obtain it from the <code>DataTypeManagerDB</code> as shown below.</p> <pre><code>datatype = data_type_manager.getDataType("/mystruct") field1 = datatype.components[0] field1_settings = field1.getDefaultSettings() field1_settings.setLong('endian', EndianSettingsDefinition.BIG) </code></pre> <p>After applying the structure to a piece data, you can right click on the field -> Data -> Default Settings and check that the default endianness is indeed Big Endian.</p> <p><a href="https://i.stack.imgur.com/tAIhg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tAIhg.png" alt="enter image description here"></a></p>
23330
2020-02-24T04:59:34.720
<p>Using ghidra's python scripting engine, I'd like to create a struct which contains a big endian, unsigned integer. This field is always big endian, no matter what the endainess of the binary CPU is.</p> <p>My first attempt:</p> <pre><code>def uint32b(): dt = UnsignedIntegerDataType() for s in dt.getSettingsDefinitions(): if isinstance(s, EndianSettingsDefinition): s.setBigEndian(dt.getDefaultSettings(), False) return dt </code></pre> <p>However, when the struct is applied to data, I'm still seeing a little-endian value. The field's "Default Settings -> Endian" still set to "Default".</p> <p><a href="https://i.stack.imgur.com/Xu89M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xu89M.png" alt="default settings"></a></p>
ghidra-python: create struct with big endian field
|python|ghidra|
<p>From <code>Radare2</code> <a href="https://radare.gitbooks.io/radare2book/configuration/intro.html" rel="noreferrer">book</a>:</p> <blockquote> <p>The core reads <code>~/.config/radare2/radare2rc</code> while starting. You can add <code>e</code> commands to this file to tune the radare2 configuration to your taste.</p> </blockquote>
23332
2020-02-24T15:27:30.397
<p>As the title says, I am trying to change the default disassembly syntax in Radare2 from Intel to AT&amp;T. Looking up documentation, I found the following.</p> <pre><code>[0x00405e1c]&gt; e asm.syntax=att </code></pre> <p>However, changing syntax this way does not persist across sessions. Is there a command I can use to save settings permanently?</p>
How do I permanently change the disassembly syntax in Radare2?
|radare2|
<p>It called <code>x-refs</code>. Go to the beginning of your routine, and press <code>ctrl+x</code> from disassembly view, or just <code>x</code> from the decompile view.</p>
23341
2020-02-26T13:47:40.060
<p>I am reversing an application using IDA. I have found a small subroutine that returns information at the end of that subroutine. However I would like to see the subroutine that uses this small subroutine I found and see how it uses the information returned by the small subroutine. </p> <p>I am new to this, is what Im trying to do a simple task, if so how can I do this? </p> <p>Thanks for the help !</p>
How to find where a subroutine is being called (ida)
|ida|disassembly|decompilation|decompile|
<p><em>Coming back to answer this question with the actual answer I was looking for now that I have some more experience and figured out what happened.</em></p> <p>When opening a binary in IDA Pro that has the Hex-Rays decompiler plugin you may open the pseudocode view using the hotkey <code>F5</code>, and also re-analyze the current function by pressing <code>F5</code> again as @Avery3R posted in his answer.</p> <p>However, if you work your way through the binary by double-clicking functions you can go back to one of the functions you already have decompiled and re-analyze it. The pseudocode will then change to reflect the changes you have done (or simply the optimizations done by the Hex-Rays decompiler). Typical changes you will see are the number of function arguments that will be adjusted to be more correct.</p> <p>Usually what I do if I encounter pseudocode that seems incorrect in terms of function arguments, I will click around and &quot;peek&quot; into the different problematic functions before I go back to the initial function I started with and re-analyze it. The pseudocode will then look way better and be easier to work with.</p> <p>And if you would like to re-analyze the whole binary you coud always do that by going to <code>Options -&gt; General -&gt; Analysis -&gt; Reanalyze program</code>, and <code>Ctrl+F5</code> to decompile all functions.</p>
23352
2020-02-27T22:23:38.777
<p>While I was reversing a binary I noticed that IDA Pro had adjusted the pseudocode that initially was generated. This happened after I started reversing the binary and renamed functions and variables to more appropriate names. IDA Pro had then "prettified" or re-analyzed the pseudocode somehow. </p> <p>I am not sure what keys I pressed or options I clicked to achieve this, but it was extremely useful. </p> <p>How can I replicate this?</p>
Re-analyzing pseudocode IDA Pro
|hexrays|
<p>This is a great question, and lucky you - radare2 provides several ways to achieve this. Let's go over the more basic and straightforward options.</p> <h2>Setting up</h2> <p>First things first, make sure to have the latest radare2 running. At the time of writing, this is v4.3.1. The radare community recommends building radare2 from the source. On Linux systems, it's as simple as cloning the <a href="https://github.com/radareorg/radare2" rel="noreferrer">repository</a> and executing the following commands:</p> <pre><code>$ cd radare2 $ ./sys/install.sh </code></pre> <p><em>Note: By installing radare2 from package-repositories you may miss crucial features due to old versions.</em></p> <p>Now that this part is behind us, we can continue to the solutions.</p> <hr> <h2>Preparing test programs</h2> <p>For the following examples, I wrote two programs to demonstrate how the data I dynamically pass from one program to the other program is reflected in its output.</p> <p><strong>repeater</strong> is a program that receives user input and prints it to the console.<br> <strong>Source:</strong> repeater.c</p> <pre><code>#include &lt;stdio.h&gt; int main() { char user_input[100]; fgets (user_input, 100, stdin); printf ("[+] Received from STDIN: %s\n", user_input); return 0; } </code></pre> <p><strong>exp</strong> is a program that prints string to the console.<br> <strong>Source:</strong> exp.c </p> <pre><code>#include &lt;stdio.h&gt; int main() { // print string, hex values, and the current UNIX time printf ("Hello, \x41\x42\xaf\xd7, %u", (unsigned)time(NULL)); return 0; } </code></pre> <p>To demonstrate the required behavior, we can use these programs like this:</p> <pre><code>$ ./exp | ./repeater [+] Received from STDIN: Hello, AB��, 1583565405 $ ./exp | ./repeater [+] Received from STDIN: Hello, AB��, 1583565418 </code></pre> <hr> <h2>Method 0: rarun2 profile</h2> <p>In radare2, when it gets to interact with a debuggee, rarun2 is your go-to tool.</p> <blockquote> <p>This program is used as a launcher for running programs with different environments, arguments, permissions, directories and overridden default file descriptors.<br> <strong>Source:</strong> <code>man rarun2</code></p> </blockquote> <p>While very complex and rich with features, we will focus on one of the basic features, interacting with STDIO.</p> <p>From your question, it is clear that you are familiar with the concept of rarun2 profiles. When I use rarun2 to pass the output of an exploit to the debuggee, I use a profile that looks somewhat like this:</p> <pre><code>$ cat profile.rr2 #!/usr/bin/rarun2 stdin=!./exp </code></pre> <p>This rarun2 profile will execute the <code>./exp</code> program and set the output of the program to the stdin of the debuggee.</p> <p>Then, we can quickly execute the program in radare2 again and again without leaving the radare2 shell.</p> <p>First, create a rarun profile as shown above. Then, open the debuggee in radare2 and load this profile using the <code>-r</code> flag:</p> <p>Load the program in debug mode and use <code>dc</code> to execute it:</p> <pre><code>$ r2 -r profile.rr2 -d repeater Process with PID 86588 started... = attach 86588 86588 [0x7f89ba9b8100]&gt; dc [+] Received from STDIN: Hello, AB��, 1583567900 </code></pre> <p>As you can see, you entered debug mode and the program was executed successfully with the output of the <code>exp</code> program. You can keep executing the program as many times as you want by using <code>doo (as well as</code>ood`) that will "Reopen in debug mode with args".</p> <pre><code>[0x7f316b76c100]&gt; doo Process with PID 86657 started... = attach 86657 86657 [0x7f2aecada100]&gt; dc [+] Received from STDIN: Hello, AB��, 1583568042 [0x7f2aec99ace6]&gt; doo Process with PID 86660 started... = attach 86660 86660 [0x7ff100166100]&gt; dc [+] Received from STDIN: Hello, AB��, 1583568056 [0x7f0efc9e4ce6]&gt; doo Process with PID 86673 started... = attach 86673 86673 [0x7f676d6b2100]&gt; # Define Breakpoint at main [0x7f676d6b2100]&gt; db main [0x7f676d6b2100]&gt; dc hit breakpoint at: 5652649de159 [0x5652649de159]&gt; dc [+] Received from STDIN: Hello, AB��, 1583568059 </code></pre> <hr> <h2>Method 1: rarun2 rule</h2> <p>Luckily, you can skip the creation of rarun2 file and just tell radare2 from where it should grab the stdin. This can be done easily by using the <code>-R</code> flag followed by rarun key and value.</p> <pre><code>$ r2 -R stdin=\!./exp -d repeater Process with PID 87508 started... = attach 87508 87508 [0x7f87588c0100]&gt; dc [+] Received from STDIN: Hello, AB��, 1583568818 </code></pre> <p>This is a one-time shot, and using <code>doo</code> again from within the radare2 session would not use the same stdin again. But, you can take advantage of the <code>dor</code> command and do some trick ;)</p> <pre><code>[0x7f8758780ce6]&gt; dor? | dor [rarun2] Comma separated list of k=v rarun2 profile options (e dbg.profile) [0x7f8758780ce6]&gt; dor stdin=!./exp [0x7f8758780ce6]&gt; doo Process with PID 87594 started... = attach 87594 87594 [0x7f8758780ce6]&gt; dc [+] Received from STDIN: Hello, AB��, 1583568991 [0x7fdb45f3ece6]&gt; # And this of course can be done with a single line [0x7fdb45f3ece6]&gt; dor stdin=!./exp; doo; dc Process with PID 87627 started... = attach 87627 87627 [+] Received from STDIN: Hello, AB��, 1583569028 </code></pre> <hr> <h2>Method ∞</h2> <p>There are other ways you can perform such set-up. Since it will be too long, I will quickly note them down. Here are some ideas:</p> <ol> <li><p>Use backticks: <code>r2 -R "stdin=\"`python -c print(1234)`\"" -d repeater</code> or even <code>r2 -R "stdin=\"`python -c 'print(1234)'`\"" -d repeater</code></p></li> <li><p>Use other terminal's tty to redirect STDIN. You can simply pass data to the tty by executing <code>./exp &gt; dev/pts/X</code> where x is the tty number.</p></li> <li><p>Use <code>popen</code> to write to the process, or redirect output to /proc//fd/0</p></li> <li><p>Use an external shell script to automate the tedious tasks you encountered</p></li> </ol>
23359
2020-02-29T04:02:44.657
<p>I wrote a C program that constructs a ROP payload and sends it to <code>stdout</code>. Using Radare2's debug mode, how would I pipe this output to a binary I am trying to exploit that accepts input on <code>stdin</code>?</p> <p>For example, if my compiled C program is <code>exp</code> and the binary I am exploiting is <code>vuln</code>, I want to execute <code>./exp | ./vuln</code> in Radare2's debug mode so I can see how my payload corrupts memory.</p> <p>I saw <a href="https://reverseengineering.stackexchange.com/questions/16428/debugging-with-radare2-using-two-terminals">this post</a> but, correct me if I am wrong, it doesn't seem to answer my question and just describes how to use a second terminal for input/output. </p> <p>Edit: I have found a workaround for the time being, but it is rather annoying to do repeatedly when I make changes. I first redirect the output to a new a file: <code>./exp &gt; exp.output</code> and then make a <code>rarun2</code> script as follows:</p> <pre><code>#!/usr/bin/rarun2 stdin=./exp.output </code></pre> <p>And then I run things via <code>r2 -e dbg.profile=dbg.rr2 -d vuln</code>.</p>
Radare2 Debugging: How do I pipe a program's output to another's input?
|radare2|
<p>In <code>C</code>, this function would look like this:</p> <pre><code>int fun() { int a; // some code you haven't pasted here; probably scanf("%d", &amp;a);... if (some_condition) a ^= 3; // xor a with 3 else a ^= 2; // xor a with 2 printf("a = %d.\n", a); return 0; } </code></pre> <p>I cannot say anything more about it having only the snipped you shared with us. If there is some magic, it is contained in the part you haven't uploaded.</p>
23364
2020-03-01T08:47:59.300
<p>I am new to reverse engineering and I am trying to figure out exactly what xor is doing in this little program. I know if I put any number other than 0 I get a xor eax,3 so if I put in 1 I get 2 if I input 2 I get 1 if I input 7 I get 4 I am just trying to understand why.</p> <p><a href="https://i.stack.imgur.com/6FpHB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6FpHB.png" alt="enter image description here"></a></p>
xor eax,3 why does the input change the way it does?
|assembly|debugging|x64dbg|xor|
<p>This turned out to be a mixture of hardware breakpoint related bugs in x64dbg (which are fixed by now), and a driver denying access to <strong>some</strong> threads of the target application (meaning the hardware breakpoint could not be set on those). If you encounter this, I suggest updating and checking OpenThread permissions, as x64dbg fails silently here :/</p>
23372
2020-03-02T09:12:07.420
<p>An application I am debugging somehow manages to clear my hardware breakpoints. I am using TitanHide and x64dbg. </p> <p>I am observing the following behaviour:</p> <ul> <li>When placing the first hw breakpoint, it is hit only once - still appears visible in x64dbg but I guess it is disabled in reality and x64dbg doesn't know that.</li> <li>When placing another breakpoint, the <strong>first</strong> breakpoint is hit exactly once. </li> </ul> <p>I am not sure what causes this obscure behaviour, but what I do know is that my hardware breakpoints are not getting hit, so I researched what could possibly clear them. I have come up with:</p> <ul> <li>ZwSetInformationThread to hide the thread from the debugger.</li> <li>SetThreadContext to reset the debug registers .</li> <li>Installing a vectored exception handler, cause an exception deliberately, and modify the context from there</li> </ul> <p>However all 3 methods should be caught by TitanHide, and exceptions should show up in the log of x64dbg (which they don't). Are there any further methods to clear hardware breakpoints?</p>
Anti-debug clearing hardware breakpoints
|windows|anti-debugging|breakpoint|
<p>The xrefs provided by IDA cover only the common ways to call a function. As an developer you could generate the function address using complex mathematics and then call the function. Such calls can't be detected by IDA - that is the general limitation of static analysis. </p> <p>BTW: Why do you NOP the function calls instead of just "NOPing" the function itself ?</p> <p>You could modify the function in a way that it does nothing: the first command jumps to the end of the function or modify it so that it directly exits the function without doing anything. Therefore it would not matter if you manage to find all code positions where the function is called. </p>
23379
2020-03-03T17:01:05.897
<p>Im trying to find where this subroutine is being called in IDA. I use xrefs to see where the subroutine is being called and I NOP the all the calls in all the subroutines in the xrefs. I do this for all the calls in the xrefs so nothing is calling this subroutine but the code in the subroutine is still being ran ingame and im so confused. is there some other place other than the xrefs where the subroutine is being called? thanks for the help</p>
IDA subroutine code running when not being called
|ida|disassembly|decompilation|
<p>You can modify the code in IDA. IDA saves internally the original as well as the patched content.</p> <p>Make your modifications using the sub menu commands of <strong>Edit -> Patch program</strong></p> <p>If your modifications are completed you can apply the modifications on an external file. To do so use menu <strong>Edit -> Patch program -> Apply patches to input file</strong>. It allows you to select an external file and apply the changes you have made to it.</p>
23392
2020-03-06T06:25:12.190
<p>Similarly to <code>retrieve_input_file_md5</code>, I was looking for a way to dump a patched input file.</p> <p>Basically, I would like to do the following:</p> <ul> <li>patch the file in IDA</li> <li>dump the patched input file to another file</li> <li>try the resulting file in an emulator (it's a PSX BIOS)</li> </ul> <p>Is this possible from within IDA ?</p>
Is it possible to dump input file?
|ida|
<p>You can use <a href="https://ghidra.re/ghidra_docs/api/ghidra/program/model/listing/Program.html#getImageBase()" rel="noreferrer"><code>currentProgram.getImageBase()</code></a> to obtain the base address. This returns an <code>Address</code> object.</p> <h3>Example</h3> <pre><code>&gt;&gt;&gt; currentProgram.getImageBase() 00400000 &gt;&gt;&gt; type(currentProgram.getImageBase()) &lt;type 'ghidra.program.model.address.GenericAddress'&gt; &gt;&gt;&gt; currentProgram.getImageBase().getOffset() 4194304L &gt;&gt;&gt; hex(currentProgram.getImageBase().getOffset()) '0x400000L' </code></pre>
23401
2020-03-08T11:07:48.550
<p>What is the way to get the program base address in <code>Ghidra</code>? </p>
Ghidra python - get program base address
|elf|ghidra|
<p>The firmware is incorrectly dumped. In your file all occurrences of the byte <code>0A</code> have been replaced with <code>0D 0A</code>. Looks like a line ending issue. May be the tool which you have used to dump the firmware have prepended a <code>0D</code> to each <code>0A</code>.</p> <p>After replacing all instances of <code>0D 0A</code> with <code>0A</code>, it has an exact size of 256 KiB (262144 bytes) as it should be. Previously it had a size of 263788 bytes ~ 257.6 KiB.</p> <p>For reference, I've uploaded the fixed firmware <a href="https://send.firefox.com/download/7c1b0606a4118766/#tMQz5dAQHmK2MsXbBKyZUA" rel="nofollow noreferrer">here</a></p> <pre><code>$ ./sfk196-linux-64.exe replace dump.bin -binary /0d0a/0a/ -yes [total hits/matching patterns/non-matching patterns] [1644/1/0] dump.bin -1644 bytes 1 files checked, 1 changed. $ du -b dump.bin 262144 dump.bin </code></pre> <p>Further you can use <a href="https://github.com/DigitalSecurity/nrf5x-tools" rel="nofollow noreferrer">nrf5x-tools</a> on the fixed firmware to verify.</p> <pre><code>$ python3 ./nrfident.py bin ../dump.bin 2&gt;/dev/null ############################ nRF5-tool ############################ ##### ##### ##### Identifying nRF5x firmwares ##### ##### ##### ################################################################### Binary file provided ../dump.bin Computing signature from binary Signature: 26d6240e598f89b8aeabcecb96f3c5595b07bfc315b969a13aca34b2e61a7dc0 Searching for signature in nRF.db ========================= SDK version: 8.1.0 SoftDevice version: s110 NRF: nrf51822 ========================= SDK version: 9.0.0 SoftDevice version: s110 NRF: nrf51822 ========================= SDK version: 10.0.0 SoftDevice version: s110 NRF: nrf51822 ========================= SDK version: 8.0.0 SoftDevice version: s110 NRF: nrf51822 ================== nRF5x signature written to file nRF_ver in current directory nRF_ver path must be provided when running nrfreverse.py from IDA ***** Binary mapping ***** SoftDevice : s110 Card version : xxaa ***** RAM address : 0x20002000 RAM length : 0x2000 ROM address : 0x18000 ROM length : 0x28000 ***** Binary mapping ***** SoftDevice : s110 Card version : xxab ***** RAM address : 0x20002000 RAM length : 0x2000 ROM address : 0x18000 ROM length : 0x8000 ***** Binary mapping ***** SoftDevice : s110 Card version : xxac ***** RAM address : 0x20002000 RAM length : 0x6000 ROM address : 0x18000 ROM length : 0x28000 </code></pre> <p>Loading the binary in Ghidra using the language <code>ARM-Cortex-32-little</code>, the code is readable.</p> <p><a href="https://i.stack.imgur.com/guQzz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/guQzz.png" alt="enter image description here"></a></p> <p>There are still some errors but those are because I have not created the memory segments. For more information look into the <a href="https://infocenter.nordicsemi.com/pdf/nRF51_RM_v3.0.pdf" rel="nofollow noreferrer">nRF51 Series Reference Manual</a>, Section - 5.</p> <p><a href="https://i.stack.imgur.com/v7L8t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v7L8t.png" alt="enter image description here"></a></p>
23431
2020-03-13T04:10:54.250
<p>I'm new to Ghidra so go easy on me. Running it on Windows.</p> <p>After successfully extracting a Bluetooth door lock's firmware from a nRF51, I proceeded to decompile it using Ghidra. My aim is to able to read some of its original source code, even though I understand it won't be as clean as the original.</p> <p>But, after analyzing the bin file, I get tons of error. Architecture used/tried to solve this issue was both the ARM Cortex LE 32 bit and the ARM v6 LE 32 bit. Looked for solutions on the internet and I did not find anyone with the same issue. All of the errors are <code>Bad Instruction</code>.</p> <p>Here's pictures of two different analyze:</p> <p>Without ARM Aggressive Instruction Finder (Prototype) <a href="https://i.stack.imgur.com/5Ipa2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Ipa2.png" alt="enter image description here"></a></p> <p>With ARM Aggressive Instruction Finder (Prototype) <a href="https://i.stack.imgur.com/n6tM7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n6tM7.png" alt="enter image description here"></a></p> <p>The reason I posted two pictures of my code browser because those two different analysis gave me different amount of bookmark. I know it's because of the Instruction Finder but who knows this might help you to help me.</p> <p>I have also tried adding a line into my <code>ia.sinc</code> file as suggested by a user named <em>nsadeveloper789</em> on a <a href="https://github.com/NationalSecurityAgency/ghidra/issues/22" rel="nofollow noreferrer">GitHub issue</a> but it did not solve my issue. I have also tried the <code>No Return</code> method from a <a href="https://initrd.net/stuff/ghidra/GhidraDocs/GhidraClass/Advanced/improvingDisassemblyAndDecompilation.pdf" rel="nofollow noreferrer">PDF lesson</a> (page 11) and no luck as well.</p> <p>Did used SVD-Loader as well but still doesn't solve the issue as the SVD-Loader's script itself might have an issue and I've commented on this issue on GitHub (currently no specific solution). You can have a look at this issue <a href="https://github.com/leveldown-security/SVD-Loader-Ghidra/issues/1" rel="nofollow noreferrer">here</a>. </p> <p>Does anyone knows how to solve this issue? I've been trying for a week or two now and even asked this in the unofficial Ghidra's Discord group but no answer yet.</p> <p>Looking forward for your answers. Thanks in advance.</p> <p>Here's a link to download the bin file: <a href="https://filebin.net/5abhimciwdfr5gfi" rel="nofollow noreferrer">https://filebin.net/5abhimciwdfr5gfi</a></p>
Tons of error bookmark on Ghidra
|firmware|ghidra|
<p>There are several ways you can achieve this. I assume you don't have source code of the executable, otherwise you would just tell the compiler to for example generate few <code>nop</code>s for you after the <code>call</code> opcode, so you would simply patch the call without any data shifting.</p> <p>As you said, you could replace the call with long call (but as far as I know all calls on x86-32 takes 4+1 bytes of space, no matter if they are relative or absolute) and shift all the instructions below because there is sometimes free space between functions generated by compiler (eg filed with 0xCC), but then you would need to fix all jumps/calls to addresses that are affected by your shift. Doing this you have to remember that there may be dynamicaly generated jump-tables/calls that you would also need to replace.</p> <p>The better approach would be to hook that function and apply short prolog and epilog to your payload. I will try to explain how it can be done. Let's say you have following assembly instructions:</p> <pre><code>0069DDCC | 8B00 | mov eax,dword ptr ds:[eax] 0069DDCE | 8B50 24 | mov edx,dword ptr ds:[eax+24] 0069DDD1 | A1 00506F00 | mov eax,dword ptr ds:[6F5000] 0069DDD6 | 8B00 | mov eax,dword ptr ds:[eax] </code></pre> <p>And you want to redirect the code flow at <code>0x69DDCE</code> to your function that is located at <code>0xDEADBEEF</code>. As you can see the instruction at <code>0x69DDCE</code> is 3 bytes long, but the long jmp is actually 5 bytes long. After patching the 5 bytes our code looks like:</p> <pre><code>0069DDCC | 8B00 | mov eax,dword ptr ds:[eax] 0069DDCE | E9 1CE143DE | jmp DEADBEEF 0069DDD3 | 5C | pop esp 0069DDD4 | 6F | outsd 0069DDD5 | 008B 00E81770 | add byte ptr ds:[ebx+7017E800],cl </code></pre> <p>This is because we have partially overwritten the <code>mov eax,dword ptr ds:[6F5000]</code> so our code will change the behavior after returning from your function at <code>0xDEADBEEF</code>. The thing we need to do here is to <code>NOP</code> the instruction totally, so in fact we need to patch 8 bytes (<code>mov edx,dword ptr ds:[eax+24]</code> + <code>mov eax,dword ptr ds:[6F5000]</code>), so it will look like this:</p> <pre><code>0069DDCC | 8B00 | mov eax,dword ptr ds:[eax] 0069DDCE | E9 1CE143DE | jmp DEADBEEF 0069DDD3 | 90 | nop 0069DDD4 | 90 | nop 0069DDD5 | 90 | nop 0069DDD6 | 8B00 | mov eax,dword ptr ds:[eax] </code></pre> <p>Now we need to prepare our payload at <code>0xDEADBEEF</code>. Keep in mind that you have removed two instructions from the original code, so you need to execute them at some point, also note the address where we should restore the original code flow, which is <code>0x69DDD6</code>. If you plan to modify the registers in your payload you need to save them, the best would be probably to call the pushad/pushfd, so the final payload at <code>0xDEADBEEF</code> can look like this</p> <pre><code>pushad pushfd ; your code popfd popad mov edx,dword ptr ds:[eax+24] mov eax,dword ptr ds:[6F5000] jmp 0x69DDD6 </code></pre> <p>The <code>mov</code>s in the payload are the ones you have deleted from original code, and the <code>jmp 0x69DDD6</code> is the place where you should restore the original flow. Keep in mind that if you write something to the program memory in your code you may change the way program executes if it will use your changed data at some point. Otherwise the program should continue normally after jumping back from your function.</p>
23433
2020-03-14T05:58:54.143
<p>What i want to do is take a PE file, extract its call-graph, and then inject a junk function in it, so for example by injecting a junk function inside of it, and changing a call instruction's opcode to point to this junk function, and then returning to the original destination after the junk code is done without changing the behavior of program</p> <p>so is there any open source program that does this so i can see how they did it? </p> <p>my idea is to create a new section in PE at the end of it, and change section headers by modifying an existing section which is not used or appending a new section header, and then change some call instruction to point to this</p> <p>the problem i think i will face is long calls, basically if the offset between junk code and call instruction is too far, then i have to change the call instruction to a far call instruction which makes things really complicated if not impossible</p> <p>so any suggestion? do you guys happen to know any open-source program that does this? or maybe i can approach this better? all i want is to change the call-graph of a PE file</p>
What is the best way to change the call-graph of a PE file without changing its real behavior and without packing it?
|windows|x86|malware|pe|
<p>After looking over the assembly source again, I realized that the last 12 characters of the code depended completely on the values of the first 4. Because of this, you can generate the last 12 characters from the first 4. The code can be lifted (as suggested by other answers) with some small modifications to the code to perform writes instead of cmp+jne. Note: The encryption method is basically a Feistel cipher.</p> <p>Below is the modified lifted code I used to generate the flag:</p> <pre><code>section .text global _start _start: call generate_code mov edx, 16 ;message length mov ecx, msg ;message to write mov ebx, 1 ;file descriptor (stdout) mov eax, 4 ;system call number (sys_write) int 0x80 ;syscall jmp _done _done: mov eax, 1 ;system call number (sys_exit) int 0x80 ;syscall generate_code: push esi push ebp mov ebp, esp mov esi, msg mov edx, 0xfa mov al, [esi] rol edx, 5 xor dl, al add dl, 0xab mov al, [esi+1] rol edx, 3 xor dl, al add dl, 0x45 mov al, [esi+2] rol edx, 1 xor dl, al add dl, 0x12 mov al, [esi+3] rol edx, 9 xor dl, al add dl, 0xcd mov cl, dl and cl, 15 add cl, 'a' mov [esi+4], cl rol edx, 12 xor dl, cl add dl, 0x87 mov cl, dl and cl, 15 add cl, 'a' mov [esi+5], cl rol edx, 3 xor dl, cl add dl, 0xef mov cl, dl and cl, 15 add cl, 'C' mov [esi+6], cl rol edx, 1 xor dl, cl add dl, 0x10 mov cl, dl and cl, 15 add cl, 'f' mov [esi+7], cl rol edx, 13 xor dl, cl add dl, 0x9a mov cl, dl and cl, 15 add cl, 'e' mov [esi+8], cl rol edx, 9 xor dl, cl add dl, 0xa8 mov cl, dl and cl, 15 add cl, 'D' mov [esi+9], cl rol edx, 7 xor dl, cl add dl, 0xca mov cl, dl and cl, 15 add cl, 'D' mov [esi+10], cl rol edx, 2 xor dl, cl add dl, 0x91 mov cl, dl and cl, 15 add cl, 'c' mov [esi+11], cl rol edx, 5 xor dl, cl add dl, 0x86 mov cl, dl and cl, 15 add cl, 'A' mov [esi+12], cl rol edx, 6 xor dl, cl add dl, 0xf1 mov cl, dl and cl, 15 add cl, 'e' mov [esi+13], cl rol edx, 3 xor dl, cl add dl, 0x1f mov cl, dl and cl, 15 add cl, 'B' mov [esi+14], cl rol edx, 4 xor dl, cl add dl, 0x90 mov cl, dl and cl, 15 add cl, 'f' mov [esi+15], cl mov al, 1 mov esp, ebp pop ebp pop esi ret section .data msg db '0000000000000000', 16 </code></pre>
23459
2020-03-18T00:50:30.810
<p>Disclaimer: I'm not asking for the solution to this problem, but for you to point out the particular areas or techniques of reverse engineering that I need to improve at in order to solve this problem myself.</p> <p>The code in question comes from the game "Sourcery," it's basically a CTF inside a game. The game doesn't give you the ability to debug or modify the code whatsoever, so the problem to solve here is to find an input that will make <code>verify_code</code> return 1.</p> <p>So far I had the idea of trying to brute force the solution, i.e. trying all possible codes until I find one that works. The range of acceptable characters for the code is all printable ascii chars, and we need to figure out 16 chars, which seems like it would take too much time to brute force unless you were able to reduce the character range.</p> <p>The thing that is making this hard for me to mentally analyze is that it seems like if you change one character, it can change the effect that successive characters have on the execution path. </p> <p>Any ideas how to approach this?</p> <pre><code>; int verify_code(char *code) verify_code: push esi push ebp mov ebp, esp sub esp, 8 push dword [ebp + 12] call strlen cmp eax, 16 ; the code must be 16 characters long. jne .bad mov esi, [ebp + 12] mov edx, 0xfa mov al, [esi] rol edx, 5 xor dl, al add dl, 0xab mov al, [esi+1] rol edx, 3 xor dl, al add dl, 0x45 mov al, [esi+2] rol edx, 1 xor dl, al add dl, 0x12 mov al, [esi+3] rol edx, 9 xor dl, al add dl, 0xcd mov cl, dl and cl, 15 add cl, 'a' cmp [esi+4], cl jne .bad rol edx, 12 xor dl, cl add dl, 0x87 mov cl, dl and cl, 15 add cl, 'a' cmp [esi+5], cl jne .bad rol edx, 3 xor dl, cl add dl, 0xef mov cl, dl and cl, 15 add cl, 'C' cmp [esi+6], cl jne .bad rol edx, 1 xor dl, cl add dl, 0x10 mov cl, dl and cl, 15 add cl, 'f' cmp [esi+7], cl jne .bad rol edx, 13 xor dl, cl add dl, 0x9a mov cl, dl and cl, 15 add cl, 'e' cmp [esi+8], cl jne .bad rol edx, 9 xor dl, cl add dl, 0xa8 mov cl, dl and cl, 15 add cl, 'D' cmp [esi+9], cl jne .bad rol edx, 7 xor dl, cl add dl, 0xca mov cl, dl and cl, 15 add cl, 'D' cmp [esi+10], cl jne .bad rol edx, 2 xor dl, cl add dl, 0x91 mov cl, dl and cl, 15 add cl, 'c' cmp [esi+11], cl jne .bad rol edx, 5 xor dl, cl add dl, 0x86 mov cl, dl and cl, 15 add cl, 'A' cmp [esi+12], cl jne .bad rol edx, 6 xor dl, cl add dl, 0xf1 mov cl, dl and cl, 15 add cl, 'e' cmp [esi+13], cl jne .bad rol edx, 3 xor dl, cl add dl, 0x1f mov cl, dl and cl, 15 add cl, 'B' cmp [esi+14], cl jne .bad rol edx, 4 xor dl, cl add dl, 0x90 mov cl, dl and cl, 15 add cl, 'f' cmp [esi+15], cl jne .bad mov al, 1 mov esp, ebp pop ebp pop esi ret 4 .bad: xor al, al mov esp, ebp pop ebp pop esi ret 4 </code></pre>
How to reason about this rotating XOR problem?
|cryptography|
<p>It is a .NPK file. The full signature is <code>NXPK</code>.</p> <p>Use the latest version of quickbms to extract the game. You can't use offzip because npk files are compressed with lz4.</p>
23468
2020-03-19T21:59:56.083
<p>I'm looking at a binary file whose starting bytes are <code>0x4E 0x58 0x50</code>. Is this an established magic number for a file format? If so, what format is it? My google-fu has proven too weak to find an answer on the intertubes.</p>
Is there a image format that starts with 0x4E 0x58 0x50 (ASCII 'NXP')?
|file-format|binary-format|
<p>Pyhidra (<a href="https://github.com/dod-cyber-crime-center/pyhidra" rel="nofollow noreferrer">github</a>, <a href="https://pypi.org/project/pyhidra/" rel="nofollow noreferrer">website</a>) is another API for interacting with Ghidra using Python.</p> <p>Pyhidra can be used within Ghidra in addition to the built-in Python runtime, but when used standalone as in these examples, the <code>from ghidra</code> imports must be inside the context manager (<code>with pyhidra.open_program(...</code>) as this essentially takes the place of opening Ghidra and loading a program.</p> <p>Here are some of the answers to this question, ported to Python 3.6+ and Pyhidra for standalone use:</p> <h2>0xec (1)</h2> <pre class="lang-py prettyprint-override"><code>import pyhidra program = 'path/to/my.exe' with pyhidra.open_program(program) as flat_api: from ghidra.program.model.block import BasicBlockModel from ghidra.util.task import TaskMonitor monitor = TaskMonitor.DUMMY currentProgram = flat_api.currentProgram for b in BasicBlockModel(currentProgram).getCodeBlocks(monitor): print(f'Label: {b.name}') print(f'Min Address: {b.minAddress}') print(f'Max Address: {b.maxAddress}') print() </code></pre> <h2>0xec (2)</h2> <pre class="lang-py prettyprint-override"><code>import pyhidra program = 'path/to/my.exe' with pyhidra.open_program(program) as flat_api: from ghidra.program.model.block import BasicBlockModel from ghidra.util.task import TaskMonitor monitor = TaskMonitor.DUMMY currentProgram = flat_api.currentProgram for block in BasicBlockModel(currentProgram).getCodeBlocks(monitor): listing = currentProgram.getListing() for ins in listing.getInstructions(block, True): print(f'{ins.getAddressString(False, True)} {ins}') print() </code></pre>
23469
2020-03-20T01:19:47.877
<p>I am using ghidra to do some reverse engineering of an ARM binary. I am wondering whether there is a way to get the basic blocks related to all the listing. Is there a function through the IDE or a script through the script manager that I could used in order to get basic blocks at least within a function. Though I found scripts to decompile the binary I couldn't find a function that listed the basic blocks. Apart from ghidra is there any other reverse engineering tools that would help me to achieve this job? Thank you!</p>
Way to get basic blocks of a binary using Ghidra
|binary-analysis|firmware|radare2|ghidra|
<p>The encryption key is stored in the variable <code>f4800b</code>. It comes out to the following byte array.</p> <pre><code>43, 57, 97, -68, -63, -61, -40, 9, 50, 87, -104, 101, 63, 34, -78, 60 </code></pre> <p>The cipher algorithm used is Triple-DES in ECB mode. It can be decrypted by the following snippet. Note that it requires the BouncyCastle Crypto provider for Java.</p> <pre><code>import java.security.*; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class Main { public static void main(String args[]) throws Exception { Security.addProvider(new BouncyCastleProvider()); byte key[] = new byte[] {43, 57, 97, -68, -63, -61, -40, 9, 50, 87, -104, 101, 63, 34, -78, 60}; //Base64 encoded cipher text here byte ct[] = Base64.getDecoder().decode("i2WZyhFJ9CZTx40Th83siw=="); Cipher instance = Cipher.getInstance("DESEDE/ECB/PKCS5Padding"); instance.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "DESede")); String pt = new String(instance.doFinal(ct)); System.out.println(pt); } } </code></pre> <h2>Sample output</h2> <p>Using the JSON snippet you provided</p> <pre><code>{ "MobileUsersBE":{ "AppVersion":"vB0gg8dKw8/ssTAXDUHLDw==\n", "DeviceCode":"NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFCjEu/IEjcEUYM4V6zswVc\n", "DeviceType":"android", "GCMCellId":"", "Password":"P4fM264BxQXhd3RQu5vk8w==\n", "UserName":"i2WZyhFJ9CZTx40Th83siw==\n" }, "ServiceUsersBE":{ "AppVersion":"ZA+PaD1HcAVZ384ENwEWBw==\n", "DeviceCode":"NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFOFoCbYVotoPrT8YV4yEHL\n", "DeviceType":"android", "Password":"t1h6/ATZ26VA8nS+fcnvkv0wtPbV8onO\n", "TransactionCode":"vfTVe1PFdoFSMOdyYSxAI33cLtBw3z3uUrzOGlZJafQYzgg+Te+n/sDv/nyll3T2", "UserName":"N67a2TEuY68jsRadkP0JGrh64aKxVin1\n" } } </code></pre> <p>Shown below are the ciphertexts and the corresponding plaintext to which it decrypts to.</p> <pre><code>vB0gg8dKw8/ssTAXDUHLDw== 2.3|138771 </code></pre> <pre><code>NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFCjEu/IEjcEUYM4V6zswVc 8f850645-36ec-350a-8bb3-09c004daeb14|36159 </code></pre> <pre><code>P4fM264BxQXhd3RQu5vk8w== test1234|364081 </code></pre> <pre><code>i2WZyhFJ9CZTx40Th83siw== test|55664 </code></pre> <p>Note that each plain text has a random number appended at the end after the <code>|</code> sign. This acts like a salt so that identical plain-texts do not encrypt to the same ciphertext.</p>
23471
2020-03-20T10:41:57.920
<p>can anyone explain the following code? is it possible to retrieve the encryption key? I think the code was heavily obfuscated in addition to obfuscation, I can recognize it is using algorithms like <strong>DESEDE</strong> with <em>CBC</em> and <em>PKCS5Padding</em> to encrypt http post traffic from the app. my question is does any one know how to retrieve the key here? </p> <pre><code>package c.e.a.a.g; import a.a; import android.util.Base64; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import java.util.regex.Pattern; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class b { /* renamed from: a reason: collision with root package name */ private static volatile b f4799a; /* renamed from: b reason: collision with root package name */ private byte[] f4800b = null; /* renamed from: c reason: collision with root package name */ private String f4801c; private b() { try { this.f4801c = a.a(new byte[]{97, 110, 100, 95, 50, 51, 116, 107, 108, 35, 95, 97, 105, 116, 33}, new byte[]{75, 24, 109, 27, -24, -51, 22, -58, -44, -74, 21, 91, -88, 48, -52, -63, 69, -67, 71, 17, 116, 77, 70, -94, 41, 121, 20, 120, 8, 121, 33, 77}); } catch (GeneralSecurityException e2) { e2.printStackTrace(); } this.f4800b = e(this.f4801c); } public static b a() { if (f4799a == null) { synchronized (b.class) { if (f4799a == null) { f4799a = new b(); } } } return f4799a; } private final String c(String str) { try { Cipher instance = Cipher.getInstance("DESEDE/ECB/PKCS5Padding"); instance.init(2, new SecretKeySpec(this.f4800b, "DESede")); return a(instance.doFinal(new a().a(str))); } catch (Exception e2) { e2.printStackTrace(); return null; } } private final String d(String str) { try { Cipher instance = Cipher.getInstance("DESEDE/ECB/PKCS5Padding"); instance.init(1, new SecretKeySpec(this.f4800b, "DESede")); try { return Base64.encodeToString(instance.doFinal(str.getBytes()), 0); } catch (IllegalBlockSizeException e2) { e2.printStackTrace(); return ""; } catch (BadPaddingException e3) { e3.printStackTrace(); return ""; } } catch (NoSuchAlgorithmException e4) { e4.printStackTrace(); } catch (NoSuchPaddingException e5) { e5.printStackTrace(); } catch (InvalidKeyException e6) { e6.printStackTrace(); } } private final byte[] e(String str) { try { return MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e2) { e2.printStackTrace(); return null; } catch (UnsupportedEncodingException e3) { e3.printStackTrace(); return null; } } public String b(String str) { StringBuilder sb = new StringBuilder(); sb.append(str); sb.append(b()); return d(sb.toString()); } private String b() { int nextInt = new Random().nextInt(999999); StringBuilder sb = new StringBuilder(); sb.append("|"); sb.append(nextInt); return sb.toString(); } public String a(String str) { return c(str).split(Pattern.quote("|"))[0]; } public b(String str) { this.f4800b = e(str); } private final String a(byte[] bArr) { StringBuffer stringBuffer = new StringBuffer(); for (byte b2 : bArr) { stringBuffer.append((char) b2); } return stringBuffer.toString(); } } </code></pre> <p>an example of encrypted http post request produced by this code is like following:</p> <pre><code>{"MobileUsersBE":{"AppVersion":"vB0gg8dKw8/ssTAXDUHLDw==\n","DeviceCode":"NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFCjEu/IEjcEUYM4V6zswVc\n","DeviceType":"android","GCMCellId":"","Password":"P4fM264BxQXhd3RQu5vk8w==\n","UserName":"i2WZyhFJ9CZTx40Th83siw==\n"},"ServiceUsersBE":{"AppVersion":"ZA+PaD1HcAVZ384ENwEWBw==\n","DeviceCode":"NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFOFoCbYVotoPrT8YV4yEHL\n","DeviceType":"android","Password":"t1h6/ATZ26VA8nS+fcnvkv0wtPbV8onO\n","TransactionCode":"vfTVe1PFdoFSMOdyYSxAI33cLtBw3z3uUrzOGlZJafQYzgg+Te+n/sDv/nyll3T2","UserName":"N67a2TEuY68jsRadkP0JGrh64aKxVin1\n"}} </code></pre>
How can I retrieve the encryption key in this code?
|android|encryption|java|patch-reversing|apk|
<p>You have missed a couple of things.</p> <ul> <li>num6 isn't used directly - it's first converted to a string and then the ascii code is used</li> <li>the first addition isn't an addition - it's a string concatenation.</li> </ul> <p>In cases like this where there are so many conversions going on, you really need to break it down and take it step at a time.</p> <p>e.g.</p> <pre><code>First Part Conversion.Oct(Strings.Asc(Conversions.ToString(num6))) = Conversion.Oct(Strings.Asc(Conversions.ToString(0))) = Conversion.Oct(Strings.Asc("0")) = Conversion.Oct(48) = "60" Second Part Conversion.Oct(Strings.Asc(@string)) = Conversion.Oct(Strings.Asc('A')) = Conversion.Oct(65) = "101" Putting it together Conversions.ToDouble("60"+ "101") + 666 = Conversions.ToDouble( "60101") + 666 = 60101 + 666 = 60767 </code></pre> <p>Alternatively, just paste the code into a simple C#/VB console application and run it to see what happens.</p>
23480
2020-03-21T00:56:39.630
<p><strong>I'm trying to solve this challenge but I can't understand the algorithm.</strong></p> <p>it takes the name and generate the serial with this algoritm</p> <pre><code>private int Encrypt(string Input) { int num = 0; checked { int num2 = Input.Length - 1; int num3 = num; int num6; for (;;) { int num4 = num3; int num5 = num2; if (num4 &gt; num5) { break; } char @string = Conversions.ToChar(Input.Substring(num3)); num6 = (int)Math.Round(unchecked(Conversions.ToDouble(Conversion.Oct(Strings.Asc(Conversions.ToString(num6))) + Conversion.Oct(Strings.Asc(@string))) + 666.0)); num3++; } return num6; } } </code></pre> <p><strong>for example, I entered 'A' and calculated serial as shown:</strong> num6 = octal + octal + decimal</p> <p>‘A’ = 65 = 101 in octal</p> <p>666 = 1232 in octal</p> <p>num6 = 0</p> <p>num6: Octal = 0 + 101 + 1232 = 1333</p> <p>Decimal = 731</p> <p>but the output is : 60767</p> <p>How?</p>
I can't understand this algorithm
|.net|